matplotlib 如何通过两个数据集(一个用于训练,另一个用于测试)绘制学习曲线?

eufgjt7s  于 2023-06-06  发布在  其他
关注(0)|答案(1)|浏览(145)

由于我使用一个过采样数据(1000)来训练随机森林模型,并使用原始数据(57)作为测试集,因此我将两个数据定义为X,y(1000)和X1,y1(57)。有人能告诉我另一种方法可以在两个数据集中绘制正确的学习曲线吗?
我尝试使用sklearn函数“learning_curve”来绘图

import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import learning_curve

df = pd.read_csv(data1)
df_data = pd.DataFrame(df)
X = df_data.drop(labels=['target'],axis=1).values
y = df_data['target'].values

df1 = pd.read_csv(data2)
df_data1 = pd.DataFrame(df1)
X1 = df_data1.drop(labels=['target'],axis=1).values
y1 = df_data1['target'].values

train_sizes, train_scores, test_scoreX = learning_curve(RandomForestClassifier(), X, y, scoring='accuracy', n_jobs=-1, train_sizes=np.linspace(0.6, 1, 100))

train_sizeX, train_scoreX, test_scores = learning_curve(RandomForestClassifier(), X1, y1, scoring='accuracy', n_jobs=-1, train_sizes=np.linspace(0.1, 1, 50))

train_mean = np.mean(train_scores, axis=1)
train_std = np.std(train_scores, axis=1)
test_mean = np.mean(test_scores, axis=1)
test_std = np.std(test_scores, axis=1)
plt.rcParams.update({'font.size': 20})
plt.subplots(1, figsize=(10,10))
plt.plot(train_sizes, train_mean, '--', color="#111111",  label="Training score")
plt.plot(train_sizes, test_mean, color="#111111", label="Test score")

plt.fill_between(train_sizes, train_mean - train_std, train_mean + train_std, color="#DDDDDD")
plt.fill_between(train_sizes, test_mean - test_std, test_mean + test_std, color="#DDDDDD")

plt.title("Random Forest Learning Curve")
plt.xlabel("Dataset Size"), plt.ylabel("Accuracy"), plt.legend(loc="best")

plt.tight_layout()
plt.show()

sklearn中的learning_curve函数不能用于绘制学习曲线,因为它们具有不同的维度ValueError: x and y must have same first dimension, but have shapes (100,) and (50,)

3phpmpom

3phpmpom1#

第二个图使用变量train_sizes。应该是train_sizeX

相关问题