我正在测试一些关于random_state
的可能性。你能解释一下random_state = 0
和random_state = numpy.random.RandomState(0)
之间的区别吗?
码
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
import numpy as np
import random
for i in range(5):
########### code for random_state= numpy.random.RandomState(i) ##############
rng = np.random.RandomState(i)
X, y = make_classification(random_state=rng)
rf = RandomForestClassifier(random_state=rng)
X_train, X_test, y_train, y_test = train_test_split(X, y,
random_state=rng)
p1=rf.fit(X_train, y_train).score(X_test, y_test)
########### code for random_state= integer ##############
X, y = make_classification(random_state=i)
rf = RandomForestClassifier(random_state=i)
X_train, X_test, y_train, y_test = train_test_split(X, y,
random_state=i)
p2=rf.fit(X_train, y_train).score(X_test, y_test)
print(i,p1,p2)
输出
0 0.84 0.92
1 1.0 0.92
2 0.88 0.92
3 0.84 0.88
4 1.0 1.0
发布于 2022-08-24 12:45:46
设置random_state = 1
设置固定种子(例如1),用于分割列车/测试集。
设置random_state = np.random.RandomState(1)
将种子设置为带有种子1的随机变量。在每次迭代时,np.random.RandomState
实例每次都会随机变化,以不可重复的方式分割集合。
如果您想要可重复的拆分,或者不使用任何具有随机拆分的值,请使用普通整数作为random_state
。
只有当你想根据特定的分布(固定的种子)随机分割你的集合时,使用RandomState
才有意义。请参阅官方关于这件事的文件
https://stackoverflow.com/questions/73472267
复制相似问题