【发布时间】:2021-09-01 16:50:00
【问题描述】:
我的代码
def lrCostFunction(theta, X, y, lambda_):
m = y.size
if y.dtype == bool:
y = y.astype(int)
tempt = theta
tempt[0] = 0
J = 0
grad = np.zeros(theta.shape)
hx = X.dot(theta.T)
h = sigmoid(hx)
J = (1/m) * np.sum(-y.dot(np.log(h)) - (1-y).dot(np.log(1-h)))
J = J + (lambda_/(2*m)) * np.sum(np.square(tempt))
grad = ((1/m) * (h - y) .dot(X)) + (lambda_/m) * tempt
return J, grad
# rand_indices = np.random.choice(m, 100, replace=False)
# sel = X[rand_indices, :]\
theta_t = np.array([-2, -1, 1, 2], dtype=float)
X_t = np.concatenate([np.ones((5, 1)), np.arange(1, 16).reshape(5, 3, order='F')/10.0], axis=1)
y_t = np.array([1, 0, 1, 0, 1])
lambda_t = 3
cost, gradient = lrCostFunction(theta_t, X_t, y_t, lambda_t)
print("J= ", cost, "\nGrad= ", gradient)
输出:
J= 3.0857279966152817
Grad= [ 0.35537648 -0.49170896 0.88597928 1.66366752]
作业要求来自相同输入的这些结果:
print('Cost : {:.6f}'.format(J))
print('Expected cost: 2.534819')
print('-----------------------')
print('Gradients:')
print(' [{:.6f}, {:.6f}, {:.6f}, {:.6f}]'.format(*grad))
print('Expected gradients:')
print(' [0.146561, -0.548558, 0.724722, 1.398003]');
我什至在互联网上搜索了每个人的代码都和我一样的答案,他们说他们的结果与预测的一样。我在我的 pycharm IDE 上复制了他们的代码,但我再次得到了相同的答案。 如果您想阅读“向量化正则化逻辑回归”的问题,输入也是相同的
链接:PYTHON ASSIGNMENT OF ANDREW NG ML COURSE
链接到具有相同代码和正确答案的解决方案之一:
链接:ONE OF THE GUYS CLAIMING TO HAVE THE EXPECTED RESULT FROM SAME CODE AS MINE
这也发生在我上次作业的一部分中,真的很令人沮丧,所以我正在寻求帮助。
【问题讨论】:
标签: python numpy machine-learning pycharm logistic-regression