gpt4 book ai didi

python - ValueError : shapes (20, 14) 和 (13,1) 未对齐 : 14 (dim 1) ! = 13(暗淡 0)

转载 作者:行者123 更新时间:2023-11-30 09:14:38 25 4
gpt4 key购买 nike

def  cal_cost(theta,X,y):
m = len(y)
predictions = X.dot(theta)
cost = (1/2*m) * np.sum(np.square(predictions-y))
return cost

def minibatch_gradient_descent(X,y,theta,learning_rate=0.01,iterations=10,batch_size =20):
m = len(y)
cost_history = np.zeros(iterations)
#n_batches = int(m/batch_size)

for it in range(iterations):
cost =0.0
indices = np.random.permutation(m)
X = X[indices]
y = y[indices]
for i in range(0,m,batch_size):
X_i = X[i:i+batch_size]
y_i = y[i:i+batch_size]

X_i = np.c_[np.ones(len(X_i)),X_i]

prediction = np.dot(X_i,theta)

theta = theta -(1/m)*learning_rate*( X_i.T.dot((prediction - y_i)))
cost += cal_cost(theta,X_i,y_i)
cost_history[it] = cost

return theta, cost_history

theta = np.zeros((X_train.shape[1], 1))
minibatch_gradient_descent(X_train,y_train,theta)

当我运行上面的代码时,我收到以下错误:

ValueError: shapes (20,14) and (13,1) not aligned: 14 (dim 1) != 13 (dim 0)

X_train.shape 为 (404,13),y_train.shape 为 (404,1)。我正在更新 theta 的值,但它仍然给我错误。

请帮忙。

最佳答案

看起来您的错误发生在 prediction = np.dot(X_i,theta) 中。如果你检查X_i的形状,它将打印出(20,14)。同样,如果您检查 theta 的形状,它将打印出 (13,1)。现在您可以明白为什么不能计算 X_itheta 的点积了。由于您使用 X_i = np.c_[np.ones(len(X_i)),X_i]X_i 添加了附加列,因此其尺寸已更改(最初是是 (20,13) )。因此,您需要向 theta 数组添加一行,以使 theta 的维度为 (14,1)

关于python - ValueError : shapes (20, 14) 和 (13,1) 未对齐 : 14 (dim 1) ! = 13(暗淡 0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59005258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com