如何在matplotlib/scikit learn中绘图?

-1 投票
2 回答
1318 浏览
提问于 2025-04-17 23:18

我正在尝试一些代码来制作学习曲线:

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 7)

from sklearn.linear_model import LinearRegression
estimator = LinearRegression()
estimator.fit(X_train, y_train)
y_predicted = estimator.predict(X_test)

fig = plt.figure()
plt.xlabel("Data")
plt.ylabel("MSE")
plt.ylim(-4, 14)
plt.scatter(X_train.ravel(), y_train, color = 'green')#<<<<<<<ERROR HERE
plt.plot(X_test.ravel(), y_predicted, color = 'blue')
plt.show()

结果是:

ValueError: x and y must be the same size

打印 X_trainy_train 的形状输出:

(1317, 11)
(1317,)

我该怎么解决这个问题呢?

2 个回答

0

问题在于,你试图将一个11维的变量(x)和一个1维的变量(y)进行绘图。你提到你想要绘制学习曲线。这意味着你是在不断训练一个模型,并在每次训练后显示错误(或者每训练5次,或者其他的)。但是你现在的做法并不是这样,你是先完全训练模型,然后再试图将输入(或者ravel()对它们做的处理)和预测结果进行绘图。这是行不通的。你需要重新考虑一下你想要实现的目标。

0

正如之前提到的,你想把响应变量和11个特征在一个二维网格上绘图,这显然是行不通的。接下来我给出的建议都无法实现你想要的效果,因为你的模型不是在不断学习,而是先分割数据,然后训练和测试。不过,如果你只是想把每个特征和响应变量逐个绘图,你可以尝试下面的做法(我用pandas来整理我的数据)。

data = DataFrame(np.random.normal(0,1, (1317, 11)), 
                     index=pd.date_range(
                     end= dt.datetime.utcnow(), 
                     periods=1317, freq='D'))

features = ['feature_{}'.format(x) for x in 
                    range(len(data.columns))]

data.columns = features
data['result'] = data.mean(1) + np.random.randn()

fig = plt.figure(figsize(10,10))
ax = fig.add_subplot(111)

for feature in features:
    ax.scatter(data[feature], data['result'], c=numpy.random.rand(3,1))  

不过我可能会直接把你的模型预测值(y_predicted)和实际值(y)散点图展示出来,这样可以更直观地验证我的模型。

enter image description here

撰写回答