用train_test_split,用for循环定义不同random_state进行svm循环
时间: 2023-11-02 08:00:53 浏览: 40
以下是用train_test_split,用for循环定义不同random_state进行svm循环的代码示例:
```python
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
# 加载数据集,X为特征,y为标签
X, y = load_dataset()
# 定义不同的random_state列表
random_states = [0, 1, 2, 3, 4]
# 定义SVM模型
svm = SVC(kernel='linear')
# 循环不同的random_state,进行train_test_split和模型训练
for random_state in random_states:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=random_state)
svm.fit(X_train, y_train)
score = svm.score(X_test, y_test)
print("random state: {}, accuracy: {:.2f}%".format(random_state, score * 100))
```
在上述代码中,我们首先定义了一组不同的random_state值,然后通过for循环逐一处理每个值。在每个循环中,我们使用train_test_split函数将数据集拆分为训练集和测试集,然后使用指定的random_state值进行拆分。接下来,我们使用SVM模型拟合训练数据,并使用测试数据评估模型性能。最后,我们将每个random_state值的模型精度打印出来。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)