【问题标题】:Logistic Regression with regularization in python failing to minimizepython中正则化的逻辑回归未能最小化
【发布时间】: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


【解决方案1】:

该实现存在两个问题:

第一个 fmin_ncg 不适合最小化。我在上一个练习中使用过它,但它无法找到具有该梯度函数的 theta,这对于 Octave 中的函数来说是理想的。

切换到

theta = fmin_bfgs(cost_function_reg, initial_theta)

解决了这个问题。

第二个问题是准确度计算错误。 一旦我使用 fmin_bfgs 进行优化,并达到与 Octave 结果相匹配的成本 (0.529),(predictions == y) 部分就会有不同的形状 ((118, 118)(118,1)),从而产生一个为 MxM 的矩阵向量。

【讨论】:

    猜你喜欢
    • 2020-10-11
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 2013-11-18
    • 2013-03-15
    • 2021-11-10
    • 1970-01-01
    • 2016-02-24
    相关资源
    最近更新 更多