logistic regression and numpy: ValueError: operands could not be broadcast together with shapes
logistic regression and numpy: ValueError: operands could not be broadcast together with shapes
这里是机器学习初学者。
在 python 3.7 中,我在尝试 运行 numpy.optimize 的 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))
这里是机器学习初学者。
在 python 3.7 中,我在尝试 运行 numpy.optimize 的 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))