我正在根据Coursera的文档在Python和Octave中实现逻辑回归。在Octave中,我成功实现了并达到了正确的训练准确率,但在Python中,由于无法访问fminunc
,我无法找到解决方法。
这是我目前的代码:
df = pandas.DataFrame.from_csv('ex2data2.txt', header=None, index_col=None)df.columns = ['x1', 'x2', 'y']y = df[df.columns[-1]].as_matrix()m = len(y)y = y.reshape(m, 1)X = df[df.columns[:-1]]X = X.as_matrix()from sklearn.preprocessing import PolynomialFeaturesfeature_mapper = PolynomialFeatures(degree=6)X = feature_mapper.fit_transform(X)def sigmoid(z): return 1/(1+np.power(np.e, z))def cost_function_reg(theta): _theta = theta.copy().reshape(-1, 1) shifted_theta = np.insert(_theta[1:], 0, 0) h = sigmoid(np.dot(X, _theta)) reg = (_lambda / (2.0*m))* shifted_theta.T.dot(shifted_theta) J = ((1.0/m)*(-y.T.dot(np.log(h)) - (1 - y).T.dot(np.log(1-h)))) + reg return Jdef gradient(theta): _theta = theta.copy().reshape(-1, 1) shifted_theta = np.insert(_theta[1:], 0, 0) h = sigmoid(np.dot(X, _theta)) gradR = _lambda*shifted_theta gradR.shape = (gradR.shape[0], 1) grad = (1.0/m)*(X.T.dot(h-y)+gradR) return grad.flatten()from scipy.optimize import *theta = fmin_ncg(cost_f, initial_theta, fprime=gradient)predictions = predict(theta, X)accuracy = np.mean(np.double(predictions == y)) * 100print 'Train Accuracy: %.2f' % accuracy
输出结果是:
Warning: Desired error not necessarily achieved due to precision loss. Current function value: 0.693147 Iterations: 0 Function evaluations: 22 Gradient evaluations: 12 Hessian evaluations: 0Train Accuracy: 50.85
在Octave中,准确率为:83.05。
任何帮助都将不胜感激。
回答:
那个实现中有两个问题:
第一个问题是,fmin_ncg
并不适合这种最小化。我在之前的练习中使用过它,但它无法找到与Octave中理想的梯度函数相匹配的theta值。
切换到
theta = fmin_bfgs(cost_function_reg, initial_theta)
解决了这个问题。
第二个问题是准确率计算错误。一旦我使用fmin_bfgs
进行优化,并达到了与Octave结果相匹配的成本值(0.529
),(predictions == y)
部分的形状不同((118, 118)
和(118,1)
),产生了一个MxM
的矩阵,而不是向量。