我一直在尝试使用fmin_cg来最小化逻辑回归的成本函数。
xopt = fmin_cg(costFn, fprime=grad, x0= initial_theta, args = (X, y, m), maxiter = 400, disp = True, full_output = True )
这是我调用fmin_cg的方式
这是我的成本函数CostFn:
def costFn(theta, X, y, m): h = sigmoid(X.dot(theta)) J = 0 J = 1 / m * np.sum((-(y * np.log(h))) - ((1-y) * np.log(1-h))) return J.flatten()
这是我的梯度函数grad:
def grad(theta, X, y, m): h = sigmoid(X.dot(theta)) J = 1 / m * np.sum((-(y * np.log(h))) - ((1-y) * np.log(1-h))) gg = 1 / m * (X.T.dot(h-y)) return gg.flatten()
似乎抛出了这个错误:
/Users/sugethakch/miniconda2/lib/python2.7/site-packages/scipy/optimize/linesearch.pyc in phi(s) 85 def phi(s): 86 fc[0] += 1---> 87 return f(xk + s*pk, *args) 88 89 def derphi(s):ValueError: operands could not be broadcast together with shapes (3,) (300,)
我知道这与我的维度有关。但我似乎无法弄清楚。我是新手,所以可能犯了明显的错误。
我读过这个链接:
fmin_cg: Desired error not necessarily achieved due to precision loss
但是,它似乎对我不起作用。
有什么帮助吗?
更新后的X,y,m,theta的尺寸
(100, 3) —-> X
(100, 1) —–> y
100 —-> m
(3, 1) —-> theta
这是我初始化X,y,m的方式:
data = pd.read_csv('ex2data1.txt', sep=",", header=None) data.columns = ['x1', 'x2', 'y'] x1 = data.iloc[:, 0].values[:, None] x2 = data.iloc[:, 1].values[:, None] y = data.iloc[:, 2].values[:, None]# join x1 and x2 to make one array of XX = np.concatenate((x1, x2), axis=1)m, n = X.shape
ex2data1.txt:
34.62365962451697,78.0246928153624,030.28671076822607,43.89499752400101,035.84740876993872,72.90219802708364,0.....
如果有帮助的话,我正在尝试用Python重新编写Andrew Ng在Coursera上的机器学习课程的一个作业
回答:
最后,我弄清楚了我的初始程序中的问题是什么。
我的’y’是(100, 1),而fmin_cg期望的是(100, )。一旦我展平了我的’y’,它就不再抛出初始错误。但优化仍然不起作用。
Warning: Desired error not necessarily achieved due to precision loss. Current function value: 0.693147 Iterations: 0 Function evaluations: 43 Gradient evaluations: 41
这与我未经优化的结果相同。
我发现优化这种情况的方法是使用’Nelder-Mead’方法。我遵循了这个答案: scipy is not optimizing and returns “Desired error not necessarily achieved due to precision loss”
Result = op.minimize(fun = costFn, x0 = initial_theta, args = (X, y, m), method = 'Nelder-Mead', options={'disp': True})#, #jac = grad)
这种方法不需要’jacobian’。我得到了我想要的结果,
Optimization terminated successfully. Current function value: 0.203498 Iterations: 157 Function evaluations: 287