Skip to main content
 首页 » 编程设计

python之如何为 scikit-learn 播种随机数生成器

2024年10月17日8youxin

我正在尝试为我的一些使用 scikit-learn 的代码编写单元测试。但是,我的单元测试似乎是不确定的。

据我所知,在我的代码中,scikit-learn 使用任何随机性的唯一地方是在它的 LogisticRegression 模型和它的 train_test_split 中,所以我有以下内容:

RANDOM_SEED = 5 
self.lr = LogisticRegression(random_state=RANDOM_SEED) 
X_train, X_test, y_train, test_labels = train_test_split(docs, labels, test_size=TEST_SET_PROPORTION, random_state=RANDOM_SEED) 

但这似乎不起作用——即使我传递了一个固定的 docs 和一个固定的 labels,固定验证集上的预测概率因运行而异运行。

我还尝试在我的代码顶部添加一个 numpy.random.seed(RANDOM_SEED) 调用,但这似乎也不起作用。

有什么我想念的吗?有没有办法在一个地方将种子传递给 scikit-learn,以便在所有 scikit-learn 的调用中使用该种子?

请您参考如下方法:

from sklearn import datasets, linear_model 
iris = datasets.load_iris() 
(X, y) = iris.data, iris.target 
RANDOM_SEED = 5 
lr = linear_model.LogisticRegression(random_state=RANDOM_SEED) 
X_train, X_test, y_train, y_test = train_test_split( 
    X, y, test_size=0.3, random_state=RANDOM_SEED) 
lr.fit(X_train, y_train) 
lr.score(X_test, y_test) 

现在多次生成 0.93333333333333335。你这样做的方式似乎没问题。另一种方式是set np.random.seed()或使用 Sacred用于记录的随机性。使用random_state 就是the docs describe :

If your code relies on a random number generator, it should never use functions like numpy.random.random or numpy.random.normal. This approach can lead to repeatability issues in unit tests. Instead, a numpy.random.RandomState object should be used, which is built from a random_state argument passed to the class or function.