sklearn如何交叉验证
时间: 2023-12-12 16:05:56 浏览: 49
scikit-learn(sklearn)提供了多种交叉验证方法,其中最常用的是K-Fold交叉验证。
K-Fold交叉验证将数据集划分为K个互不相交的子集,每个子集都尽可能保持数据集的均衡。然后选择一个子集作为测试集,其余K-1个子集作为训练集,进行模型的训练和测试。这个过程重复K次,每个子集都被用作一次测试集,最终返回K个测试结果的平均值作为模型的性能评估。
下面是一个使用K-Fold交叉验证的例子:
```python
from sklearn.model_selection import KFold
from sklearn.linear_model import LinearRegression
from sklearn.datasets import load_boston
data = load_boston()
X = data['data']
y = data['target']
kf = KFold(n_splits=5, shuffle=True, random_state=42)
for train_index, test_index in kf.split(X):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
model = LinearRegression()
model.fit(X_train, y_train)
score = model.score(X_test, y_test)
print('Test score: {:.2f}'.format(score))
```
在这个例子中,我们使用了波士顿房价数据集,并将数据集划分为5个互不相交的子集。然后我们使用LinearRegression模型对每个子集进行训练和测试,并计算模型在测试集上的R2分数。最终输出了5个测试结果的平均值。
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)