"计算成本"
def compute_cost(AL, Y):
m = Y.shape[1]
logprobs = np.multiply(np.log(AL), Y) + np.multiply(np.log(1-AL), (1-Y))
cost = (-1 / m) * np.sum(logprobs)
cost = np.squeeze(cost)
assert(cost.shape == ())
return cost
#test compute_cost
print("==========test compute_cost==========")
AL, Y = testCases.compute_cost_test_case()
cost = compute_cost(AL, Y)
print("cost = " + str(cost))
这里出现以下错误:
==========test compute_cost==========
cost = inf
D:/wuenda/wnd_weekfour/wnd_week4.py:137: RuntimeWarning: divide by zero encountered in log
logprobs = np.multiply(np.log(AL), Y) + np.multiply(np.log(1-AL), (1-Y))
问题原因:1-AL或AL可能会等于0,那么log(1-AL)和log(AL)会变得没有意义
解决办法:
在log(1-AL)和log(AL)的AL加上1e-3类似的数
logprobs = np.multiply(np.log(AL+1e-3), Y) + np.multiply(np.log(1-AL+1e-3), (1-Y))
此时output:
==========test compute_cost==========
cost = 2.0716269334614825