我正在使用scikit-learn训练一些分类器。我进行交叉验证,然后计算AUC。但是,尽管我确保使用种子和RandomState,但每次运行测试时,我都会得到一个不同的AUC编号。我希望我的测试具有确定性。这是我的代码:

from sklearn.utils import shuffle
SEED = 0
random_state = np.random.RandomState(SEED)
X, y = shuffle(data, Y, random_state=random_state)
X_train, X_test, y_train, y_test = \
        cross_validation.train_test_split(X, y, test_size=test_size, random_state=random_state)
clf = linear_model.LogisticRegression()
kfold = cross_validation.KFold(len(X), n_folds=n_folds)
mean_tpr = 0.0
mean_fpr = np.linspace(0, 1, 100)

for train, test in kfold:
        probas_ = clf.fit(X[train], Y[train]).predict_proba(X[test])
        fpr, tpr, thresholds = roc_curve(Y[test], probas_[:, 1])
        mean_tpr += interp(mean_fpr, fpr, tpr)
        mean_tpr[0] = 0.0

mean_tpr /= len(kfold)
mean_tpr[-1] = 1.0
mean_auc = auc(mean_fpr, mean_tpr)

我的问题:
1-我的代码中是否有什么错误会使每次运行结果都不相同?
2-是否有使scikit具有确定性的全局方法?

编辑:

我只是试过这个:
test_size = 0.5
X = np.random.randint(10, size=(10,2))
Y = np.random.randint(2, size=(10))
SEED = 0
random_state = np.random.RandomState(SEED)
X_train, X_test, y_train, y_test = \
    cross_validation.train_test_split(X, Y, test_size=test_size, random_state=random_state)

print X_train # I recorded the result

然后我做了:
X_train, X_test, y_train, y_test = \
    cross_validation.train_test_split(X, Y, test_size=test_size, random_state=6) #notice the change in random_state

然后我做了:
X_train, X_test, y_train, y_test = \
    cross_validation.train_test_split(X, Y, test_size=test_size, random_state=random_state)

print X_train #the result is different from the first one!!!!

如您所见,尽管我使用了相同的random_state,但结果却有所不同!怎么解决呢?

最佳答案

LogisticRegression在内部使用随机性,并具有(未记录,稍后将修复)random_state参数。

没有设置随机状态的全局方法,因为不幸的是,LogisticRegression和SVM代码上的随机状态只能以hacky的方式进行设置。这是因为此代码来自Liblinear和LibSVM,它们使用C标准库的rand函数,并且不能以有原则的方式进行播种。

编辑以上是正确的,但可能不是问题的原因。您正在通过调用线程处理单个np.random.RandomState,同时应传递相同的整数种子以简化重现性。

关于python - 使scikit具有确定性?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23445420/

10-16 13:10