我认为(hypo-y)部分有问题。
hypo
形状良好
(100,)
和
y
形状良好
(100, 1)
. 在元素方面
-
活动
海波
广播到形状
(1, 100)
broadcasting rules
. 这会导致
(100, 100)
数组,这会导致矩阵乘法产生
(3, 100)
大堆
通过带来
形状与相同
y
:
hypo = sigmoid(np.matmul(X, theta)).reshape(-1, 1) # -1 means automatic size on first dimension
还有一个问题:
scipy.optimize.minimize
(k,)
但是功能
gr
返回形状向量
(k, 1)
. 这很容易修复:
return grad.reshape(-1)
最终功能变为
def gr(theta,X,y):
m=len(y)
hypo=sigmoid(np.matmul(X,theta)).reshape(-1, 1)
grad=(1/m)*(np.matmul(X.T,(hypo-y)))
return grad.reshape(-1)
theta = np.reshape([1, 2, 3], 3, 1)
X = np.random.randn(100, 3)
y = np.round(np.random.rand(100, 1))
optim = minimize(CF, theta, method='BFGS', jac=gr, args=(X,y))
print(optim)
# fun: 0.6830931976615066
# hess_inv: array([[ 4.51307367, -0.13048255, 0.9400538 ],
# [-0.13048255, 3.53320257, 0.32364498],
# [ 0.9400538 , 0.32364498, 5.08740428]])
# jac: array([ -9.20709950e-07, 3.34459058e-08, 2.21354905e-07])
# message: 'Optimization terminated successfully.'
# nfev: 15
# nit: 13
# njev: 15
# status: 0
# success: True
# x: array([-0.07794477, 0.14840167, 0.24572182])