训练Logistic回归的一种方法是使用随机梯度下降,scikit-learn提供了接口。
我想做的是使用scikit-learn的SGDClassifier,并使其得分与此处的Logistic回归相同。但是,我必须错过一些机器学习增强功能,因为我的分数并不相同。
这是我当前的代码。我在SGDClassifier上缺少什么,它会产生与Logistic回归相同的结果?
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import SGDClassifier
import numpy as np
import pandas as pd
from sklearn.cross_validation import KFold
from sklearn.metrics import accuracy_score
# Note that the iris dataset is available in sklearn by default.
# This data is also conveniently preprocessed.
iris = datasets.load_iris()
X = iris["data"]
Y = iris["target"]
numFolds = 10
kf = KFold(len(X), numFolds, shuffle=True)
# These are "Class objects". For each Class, find the AUC through
# 10 fold cross validation.
Models = [LogisticRegression, SGDClassifier]
params = [{}, {"loss": "log", "penalty": "l2"}]
for param, Model in zip(params, Models):
total = 0
for train_indices, test_indices in kf:
train_X = X[train_indices, :]; train_Y = Y[train_indices]
test_X = X[test_indices, :]; test_Y = Y[test_indices]
reg = Model(**param)
reg.fit(train_X, train_Y)
predictions = reg.predict(test_X)
total += accuracy_score(test_Y, predictions)
accuracy = total / numFolds
print "Accuracy score of {0}: {1}".format(Model.__name__, accuracy)
我的输出:
Accuracy score of LogisticRegression: 0.946666666667
Accuracy score of SGDClassifier: 0.76