不同交叉验证划分方式python代码
时间: 2023-10-16 17:14:52 浏览: 76
神经网络python源码分享
下面是常见的三种交叉验证划分方式的Python代码实现:
1. 简单交叉验证(Hold-Out Validation)
```python
from sklearn.model_selection import train_test_split
# X为数据特征,y为数据标签
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
```
2. K折交叉验证(K-Fold Cross Validation)
```python
from sklearn.model_selection import KFold
# X为数据特征,y为数据标签,n_splits为折数
kf = KFold(n_splits=5, random_state=0, shuffle=True)
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]
```
3. 层次交叉验证(Stratified K-Fold Cross Validation)
```python
from sklearn.model_selection import StratifiedKFold
# X为数据特征,y为数据标签,n_splits为折数
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
for train_index, test_index in skf.split(X, y):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
```
阅读全文