我在尝试为我的逻辑回归模型绘制学习曲线,但即使我调整了array = np.linspace(0, dataframe.shape[0])
以适应输入参数的形状,我还是得到了下面的错误。是否可能存在某种数据丢失?因为我发现预期值与输入数据之间有超过225,000行的差异,但我不知道问题出在哪里。
def get_learning_curves(dataframe, model, X, y):#检查过拟合
array = np.linspace(0, dataframe.shape[0])
train_sizes = array.astype(int)
# 使用`learning_curve`获取训练分数(R2)、训练大小和验证分数
train_sizes, train_scores, test_scores = learning_curve(
estimator=model, X=X, y=y, train_sizes=train_sizes, cv=5)
# 计算交叉验证的训练分数和验证分数的平均值
train_scores_mean = np.mean(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
plt.plot(train_sizes, train_scores_mean, label = '训练分数')
plt.plot(train_sizes, test_scores_mean, label = '测试分数')
plt.ylabel('r2 分数', fontsize = 14)
plt.xlabel('训练集大小', fontsize = 14)
plt.title('学习曲线', fontsize = 18, y = 1.03)
plt.legend()
return plt.show()
get_learning_curves(pre, LogisticRegression(), X_pre, y_pre)
pre.shape>>>(125578, 23)
我得到的错误是:
ValueError: train_sizes 被解释为训练样本的绝对数量,必须在 (0, 100462] 范围内,但实际在 [0, 125578] 范围内。
回答:
您得到的错误信息已经很明确,意思是:
训练样本的绝对数量必须至少为1,且不能超过100462
这是因为learning_curve
使用了交叉验证。显然,交叉验证会保留k
个折叠中的1个来测试模型。假设n
是样本的绝对数量,这意味着n/k
个样本将被保留用于测试模型。反过来,这意味着您最多可以指定n - n/k
作为训练模型的子集样本大小。这就是为什么在您的案例中边界是125578 - 125578/5 = 100462
。
要解决您的问题,您需要在代码中指定正确的区间来选择样本大小。如果您想使用绝对数量来表示大小,一种方法可以是将:
array = np.linspace(0, dataframe.shape[0])
改为
array = np.linspace(1, int(dataframe.shape[0]*0.8))
这个解决方案将尊重5折交叉验证方法的边界。