我已经为非正则逻辑回归成本函数和寻找梯度编写了一些代码,但是无论我尝试什么,我的代码都会不断返回相同的TypeError。
我已经尝试过对代码进行矢量化和for循环实现,但没有任何效果。我还要指出的是,评分者总是对我的成本函数进行满分评分,而不是对偏导数进行查找的代码。我的结果始终符合预期的费用,但渐变部分没有任何回报。
它说这是成本: J(?)= 1?∑? =1?[-?(?)log(ℎ?(?(?)))-(1-?(?))log(1-ℎ?(?(?)))] >
这是偏导数: ∂?(?)∂?? = 1?∑? =1?(ℎ?(?(?))−?(?))?(?)?
(通过本课程的学习,我可以验证这是正确的)
def costFunction(theta,X,y):
# Initialize some useful values
m = y.size # number of training examples
# You need to return the following variables correctly
J = 0
grad = np.zeros(theta.shape)
# ====================== YOUR CODE HERE ============
for i in range(m):
hypothesis = sigmoid(np.dot(theta.T,X[i,:]))
J += y[i] * math.log(hypothesis) + (1 - y[i]) * math.log(1 - hypothesis)
for j in range(n):
grad = (hypothesis - y[i]) * X[i,j]
J = (-1 / m) * J
grad = (1 / m) * grad
# =============================================================
return J,grad
# Initialize fitting parameters
initial_theta = np.zeros(n+1)
cost,grad = costFunction(initial_theta,y)
print('Cost at initial theta (zeros): {:.3f}'.format(cost))
print('Expected cost (approx): 0.693\n')
print('Gradient at initial theta (zeros):')
#print('\t[{:.4f},{:.4f},{:.4f}]'.format(*grad))
print('Expected gradients (approx):\n\t[-0.1000,-12.0092,-11.2628]\n')
# Compute and display cost and gradient with non-zero theta
test_theta = np.array([-24,0.2,0.2])
cost,grad = costFunction(test_theta,y)
print('Cost at test theta: {:.3f}'.format(*cost))
print('Expected cost (approx): 0.218\n')
print('Gradient at test theta:')
print('\t[{:.3f},{:.3f},{:.3f}]'.format(*grad))
print('Expected gradients (approx):\n\t[0.043,2.566,2.647]')
我希望输出为:
Cost at initial theta (zeros): 0.693
Expected cost (approx): 0.693
Gradient at initial theta (zeros):
[-0.1000,-11.2628]
Expected gradients (approx):
[-0.1000,-11.2628]
但是我得到以下信息:
Cost at initial theta (zeros): 0.693
Expected cost (approx): 0.693
Gradient at initial theta (zeros):
Expected gradients (approx):
[-0.1000,-11.2628]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-35-ab2a7b541269> in <module>()
15 cost,y)
16
---> 17 print('Cost at test theta: {:.3f}'.format(*cost))
18 print('Expected cost (approx): 0.218\n')
19
TypeError: format() argument after * must be an iterable,not numpy.float64