from sklearn import datasets
from sklearn import model_selection

#引入sklearn库中手写数字的数据集
digits = datasets.load_digits()

#留出法
X_train, X_test, y_train, y_test = model_selection.train_test_split(digits.data, digits.target, test_size = 0.2, shuffle = True)

#K折交叉验证
#设置K为5
kf = model_selection.KFold(n_splits=5)
#使用5折交叉验验证划分数据集,返回一个生成器对象(即索引)
digits_gen = kf.split(digits.data)
for train_idx, test_idx in digits_gen:
        X_train = digits.data[train_idx] #训练集
        X_test = digits.data[test_idx] #测试集
        y_train = digits.target[train_idx] #训练集标签
        y_test = digits.target[test_idx] #测试及标签

#留一法交叉验证
loo = model_selection.LeaveOneOut()
digits_gen = loo.split(digits.data)
for train_idx, test_idx in digits_gen:
        X_train = digits_gen[train_idx]
        X_test = digits_gen[test_idx]
        y_train = digits_gen[train_idx]
        y_test = digits_gen[test_idx]