Python5折交叉验证代码
时间: 2024-02-16 11:57:03 浏览: 134
python实现交叉验证
以下是Python实现5折交叉验证的代码:
```python
from sklearn.model_selection import KFold
# 假设数据集为data和label
data = ...
label = ...
# 定义5折交叉验证
kf = KFold(n_splits=5)
# 遍历每一折
for train_index, test_index in kf.split(data):
# 获取训练集和测试集
train_data, train_label = data[train_index], label[train_index]
test_data, test_label = data[test_index], label[test_index]
# 在训练集上训练模型
model = ...
model.fit(train_data, train_label)
# 在测试集上测试模型
score = model.score(test_data, test_label)
print("Accuracy:", score)
```
阅读全文