[模型可视化]绘制学习曲线--learning_curve

#  绘制学习率
import numpy as np
import matplotlib.pyplot as plt
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.datasets import load_digits
from sklearn.model_selection import learning_curve
from sklearn.model_selection import ShuffleSplit
 
 
def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,
                        n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):
    plt.figure(figsize=(10,7))
    plt.title(title)
    if ylim is not None:
        plt.ylim(*ylim)
    plt.xlabel("Training examples")
    plt.ylabel("Score")
    train_sizes, train_scores, test_scores = learning_curve(
        estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
    train_scores_mean = np.mean(train_scores, axis=1)
    train_scores_std = np.std(train_scores, axis=1)
    test_scores_mean = np.mean(test_scores, axis=1)
    test_scores_std = np.std(test_scores, axis=1)
    plt.grid()
 
    plt.fill_between(train_sizes, train_scores_mean - train_scores_std,
                     train_scores_mean + train_scores_std, alpha=0.1,
                     color="r")
    plt.fill_between(train_sizes, test_scores_mean - test_scores_std,
                     test_scores_mean + test_scores_std, alpha=0.1, color="g")
    plt.plot(train_sizes, train_scores_mean, 'o-', color="r",
             label="Training score")
    plt.plot(train_sizes, test_scores_mean, 'o-', color="g",
             label="Cross-validation score")
 
    plt.legend(loc="best")
    return plt
 
 
digits = load_digits()
X, y = digits.data, digits.target    # 加载样例数据
 
# 图一
title = r"Learning Curves (Naive Bayes)"
cv = ShuffleSplit(n_splits=100, test_size=0.2, random_state=0)
estimator = GaussianNB()    #建模
plot_learning_curve(estimator, title, X, y, ylim=(0.7, 1.01), cv=cv, n_jobs=1)
 
# 图二
title = r"Learning Curves (SVM, RBF kernel, $\gamma=0.001$)"
cv = ShuffleSplit(n_splits=10, test_size=0.2, random_state=0)
estimator = SVC(gamma=0.001)    # 建模
plot_learning_curve(estimator, title, X, y, (0.7, 1.01), cv=cv, n_jobs=1)
 
# 
title = r"Learning Curves (LightGBM) "
cv = ShuffleSplit(n_splits=10, test_size=0.2, random_state=0)
estimator = lgbm.LGBMRegressor(num_iterations=500, learning_rate=0.01, objective='regression',
                        max_depth=6, num_leaves=2**5, min_child_samples=5,bagging_fraction = 0.8,
                        feature_fraction = 1, reg_alpha=0.01, reg_lambda=0.01)
# gbm.fit(X_train, y_train, eval_set=[(X_valid, y_valid)], eval_metric=['mae','rmse'], early_stopping_rounds=40)
plot_learning_curve(estimator, title, X, y, (-0.1, 1.01), cv=cv, n_jobs=-1)
plt.show()

在这里插入图片描述

Python中,我们可以使用`sklearn`库中的`plot_learning_curve`函数来绘制随机森林分类模型学习曲线学习曲线是一种可视化技术,它可以帮助我们理解模型性能随训练数据量增加的情况。以下是基本步骤: 1. 首先,你需要安装必要的库,如`matplotlib`和`scikit-learn`。如果还没有安装,可以使用`pip install matplotlib scikit-learn`命令。 2. 导入所需的模块: ```python import numpy as np from sklearn.datasets import make_classification from sklearn.model_selection import learning_curve from sklearn.ensemble import RandomForestClassifier import matplotlib.pyplot as plt ``` 3. 生成一些示例数据并划分训练集和测试集: ```python X, y = make_classification(n_samples=1000, n_features=20, random_state=42) train_sizes, train_scores, test_scores = learning_curve(RandomForestClassifier(), X, y, train_sizes=np.linspace(0.1, 1.0, 10), cv=5, scoring='accuracy') ``` `make_classification`用于创建模拟数据,`learning_curve`则负责生成训练集大小变化的学习分数。 4. 绘制训练集和测试集的学习曲线: ```python plt.figure() plt.title('Learning Curves (Random Forest Classifier)') plt.plot(train_sizes, train_scores.mean(axis=1), label='Training Score') plt.plot(train_sizes, test_scores.mean(axis=1), label='Cross-validation Score') plt.xlabel('Training examples') plt.ylabel('Score') plt.legend(loc='best') plt.grid() plt.show() ``` 这将显示随着训练样本数量增加,训练误差和交叉验证误差的变化情况,帮助评估模型是否过拟合或欠拟合。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值