【发布时间】:2019-10-28 00:22:18
【问题描述】:
我正在实施 Andrew ng 的 Python 机器学习课程。在编程练习 2 中,在第一个问题上,我得到了成本函数和梯度的写答案,但是当计算优化 theta 时,我得到了一个灾难性的答案!
我已经尽力了,但找不到错误
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def cost_compute( theta,x, y):
J = (-1/m) * np.sum(np.multiply(Y, np.log(sigmoid(X @ theta)))
+ np.multiply((1-Y), np.log(1 - sigmoid(X @ theta))))
return J
[m, n] = X.shape
X = np.hstack( (np.ones((m,1)) , X) )
Y = Y[:, np.newaxis]
theta = np.zeros((n+1,1))
def grad( theta, X, Y):
temp = (1/m) * X.T @ (sigmoid(X @ theta) - Y)
return temp
temp = opt.fmin_tnc(func = cost_compute, x0 = theta.flatten() , fprime = grad , args = (X, Y.flatten()))
print(temp)
预期成本是 0.693,我知道了。 预期的毕业生也与实际答案完全相同。 但是我得到的优化的 theta 是数组([4.42735730e-05, 5.31690927e-03, 4.98646266e-03],给了我大约 60 的新成本!(而不是 0.203)
【问题讨论】:
标签: python-3.x numpy machine-learning optimization scipy