如何找到给出最佳分数的列车测试分割的最佳随机状态值?

2024-06-26 09:55:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我对我的数据进行了一次列车测试,并用支持向量机对其进行了拟合

xtrain, xtest, ytrain, ytest = train_test_split(df, target)

svc = svm.SVC(C=30, gamma='auto')
svc.fit(xtrain,ytrain)
svc.score(xtest,ytest)

我正在将SVC模型拟合到iris数据集,每次运行train_test_split都会得到不同的结果(这是显而易见的)

是否有任何属性或函数train test_test_split或任何其他方式,以便在获得结果(执行上述代码后)后,我可以找出获得结果的random_state的值是多少


Tags: 数据testtargetdftrain向量split列车
1条回答
网友
1楼 · 发布于 2024-06-26 09:55:49

您可以运行自制的网格搜索来查找random_state的最佳值

但是,您永远不应该针对随机性进行优化。通过这样做,您将找到最适合某个随机事件的模型,根据定义,该随机事件与您的目标变量没有因果关系

如果您真的想继续,那么您必须记录每个随机状态的分割结果

import numpy as np
import pandas as pd

# Array of random_state values from -100 to 100
random_states = np.arange(start=-100, stop=101)

# Initialize a list where we'll store the score of each random_state
scores = []

# Initialize search
for state in random_states:
    xtrain, ytrain, xtest, ytest = train_test_split(df, target, random_state=state)
    svc = svm.SVC(C=30, gamma='auto')
    svc.fit(xtrain, ytrain)
    scores.append(svc.score(xtest, ytest))

现在将这两个阵列放在一个数据帧中

results = pd.DataFrame({'random_state':random_states, 'score':scores})
results[results['score'] == results['score'].max()]

相关问题 更多 >