使用正则化的逻辑回归在Python中未能最小化

我正在根据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的矩阵,而不是向量。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注