Role of random_state in train_test_split and classifiers
基于以下答案:Scikit学习中的随机状态(伪随机数),如果我使用与
但,
1 2 3 | for test_size in test_sizes: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=42) clf = SVC(C=penalty, probability=False) |
假设我有这样的代码。在这种情况下,我要在每个循环中更改
此外,
1 2 3 4 | clf = tree.DecisionTreeClassifier(random_state=0) scores = cross_validate(clf, X_train, y_train, cv=cv) cross_val_test_score = round(scores['test_score'].mean(), prec) clf.fit(X_train, y_train) |
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by np.random.
假设对多个测试大小中的每一个都多次执行以下行:
1 | clf = tree.DecisionTreeClassifier(random_state=0) |
如果我保留
(在这里,
1:由于您正在更改测试大小,因此随机状态不会影响测试大小之间的所选行,而且无论如何这不一定是理想的行为,因为您只是尝试基于各种样本大小来获取分数。这将为您做的是,允许您比较使用输入数据的模型,这些模型按相同的随机状态划分。从一个循环到下一个循环,测试集将完全相同。使您可以正确比较相同样本上的模型性能。
2:对于决策树分类器等模型,有一些初始化参数是随机设置的。此处的随机状态确保从一次运行到下一次运行将这些参数设置为完全相同,从而产生可重现的行为。
3:如果测试大小不同,并且乘以100,则将为每个测试集创建不同的随机状态。但是从一次完整运行到下一次运行将创建可复制的行为。您可以在那里轻松地设置静态值。
并非所有模型都以相同的方式使用随机状态,因为每个模型都有随机设置的不同参数。对于RandomForest,它正在选择随机特征。对于神经网络,它正在初始化随机权重。等等。
您可以使用以下代码进行检查:
1 2 3 4 5 6 7 | import pandas as pd from sklearn.model_selection import train_test_split test_series = pd.Series(range(100)) size30split = train_test_split(test_series,random_state = 42,test_size = .3) size25split = train_test_split(test_series,random_state = 42,test_size = .25) common = [element for element in size25split[0] if element in size30split[0]] print(len(common)) |
输出为70,表明它只是将元素从测试集中移动到训练集中。
What does random_state do here?
创建名为