我试图在Python中为logistic回归实现以下梯度下降函数:
这是我的python实现:
def gradient(X, y, theta):
dtheta = -(np.dot(X.T,y - np.exp(X * theta)))
return dthetaX是大小的数据:(2458,31),y是大小的数据:(2458,1) theta是大小的数据:(2458,1)
当我将值传递给梯度下降函数时,它返回一个大小为(31,31)的dtheta参数,由于该参数不能更新我的θ以将其传递给代价函数,所以我无法找出我出错的地方。任何帮助都将不胜感激。
我一直收到的错误是:ValueError: operands could not be broadcast together with shapes (2458,1) (31,31)
这就是我如何实现算法:
theta = np.random.uniform(low=-0.1,high=0.1, size=(2458,1))
# Iterate and update theta by using the gradient of the negative log-likelihood
max_iter = 100
learning_rate = 1e-3
for i in range(max_iter):
# Calculate the gradient
dtheta = gradient(X,y,theta)
# Update theta
theta = (theta - learning_rate) * dtheta
# Calculate the value of the log-likelihood
cost = negative_loglikelihood(X,y,theta)
# Print iteration
print("Iteration %d, cost function %.3f" % (i+1,cost))发布于 2019-11-04 05:39:47
检查您的theta尺寸。
最有可能的是,您的X维度表明每次迭代都有2458训练样本,每个迭代都有31特性。因此,您的theta应该是形状(31, 1)的矩阵。
由于X具有形状(2458, 31),如果theta具有形状(31, 1),则X*theta将具有与y相同的维度(2458, 1)和预期的尺寸。现在,y-theta具有与y或theta相同的维度。exp(y-theta)也是
X_T具有形状(31, 2458),因此,d_theta = - X_T*exp(y-theta)将具有形状(31, 1),与我们最初假定的theta形状相同,现在,您可以从theta中减去d_theta。
https://datascience.stackexchange.com/questions/62628
复制相似问题