【发布时间】:2015-08-28 06:05:48
【问题描述】:
我正在基于 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 PolynomialFeatures
feature_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 J
def 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)) * 100
print '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: 0
Train Accuracy: 50.85
以八度为单位,精度为:83.05。
感谢任何帮助。
【问题讨论】:
-
我会尝试使用几种不同的优化器,docs.scipy.org/doc/scipy/reference/optimize.html,看看 bfgs 的性能是否比 ncg 好
-
我在不提供 fprime 的情况下尝试了 bfgs,它给出了相似的结果(准确率约为 50%)。使用 fprime(那里的梯度函数)我得到一个错误。
-
如果您已经在导入 sklearn,为什么不直接使用它的逻辑回归分类器来为您完成工作呢?或者这更像是一种学习练习?
-
这是一个学习练习。我想实现自己的,以便将来更好地使用该工具。
标签: python numpy machine-learning