机器学习初学者。
在Python 3.7中,我在尝试运行numpy.ptimize的fmin_tnc
时不断遇到此错误。
我知道这种类型的问题已经多次问过,但是尽管检查了我的矩阵维度和代码几次,但我找不到我的错误。
这是功能:
def compute_cost(theta, X, y, lambda_):
m = len(y)
mask = np.eye(len(theta))
mask[0,0] = 0
hypo = sigmoid(X @ theta)
func = y.T @ np.log(hypo) + (1-y.T) @ np.log(1-hypo)
cost = -1/m * func
reg_cost = cost + lambda_/(2*m) * (mask@theta).T @ (mask@theta)
grad = 1/m * X.T@(hypo-y) + lambda_/m * (mask@theta)
return reg_cost.item(), grad
这是我的尺寸:
X: (118, 3)
y: (118, 1)
theta: (3, 1)
功能调用,
initial_theta = np.zeros((3,1))
lambda_ = 1
thetopt, nfeval, rc = opt.fmin_tnc(
func=compute_cost,
x0=initial_theta,
args=(X, y, 1)
)
和错误。
File "<ipython-input-21-f422f885412a>", line 16, in compute_cost
grad = 1/m * X.T@(hypo-y) + lambda_/m * (mask@theta)
ValueError: operands could not be broadcast together with shapes (3,118) (3,)
感谢您的帮助!
在scipy.optimize.tnc中,fmin_tnc函数调用_minimize_tnc,它似乎可以进行繁重的举重。在此功能中,它几乎是第一件事(第348行)将其弄平x0:
x0 = asfarray(x0).flatten()
所以您需要做的就是将其重塑在您的功能中。只需在您的Compute_cost函数的乞讨中添加此行:
theta = theta.reshape((3, 1))