scikit-learn_cross_validation2

2017-05-16  本文已影响51人  Ledestin

主要介绍scikit-learn中的交叉验证
sklearn.learning_curve 中的 learning curve 可以很直观的看出我们的 model 学习的进度, 对比发现有没有 overfitting 的问题. 然后我们可以对我们的 model 进行调整, 克服 overfitting 的问题.


Demo1.py

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.cross_validation import train_test_split
from sklearn.svm import SVC
from sklearn.learning_curve import learning_curve
from sklearn.cross_validation import cross_val_score 


# 加载数据集
digits = load_digits()
X = digits.data
y = digits.target
# 用SVM进行学习并记录loss
train_sizes, train_loss, test_loss = learning_curve(SVC(gamma = 0.001), 
                                                    X, y, cv = 10, scoring = 'mean_squared_error',
                                                    train_sizes = [0.1, 0.25, 0.5, 0.75, 1])

# 训练误差均值
train_loss_mean = -np.mean(train_loss, axis = 1)
# 测试误差均值
test_loss_mean = -np.mean(test_loss, axis = 1)

# 绘制误差曲线
plt.plot(train_sizes, train_loss_mean, 'o-', color = 'r', label = 'Training')
plt.plot(train_sizes, test_loss_mean, 'o-', color = 'g', label = 'Cross-Validation')

plt.xlabel('Training data size')
plt.ylabel('Loss')
plt.legend(loc = 'best')
plt.show()

结果:


Paste_Image.png

sklearn.learning_curve.learning_curve

上一篇下一篇

猜你喜欢

热点阅读