Python 多重线性回归无法绘图

我在尝试运行多重线性回归,但我在绘制结果时遇到了麻烦。我试图绘制3D图,但得到的输出是 ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (4,) and requested shape (34,)

from sklearn.model_selection import train_test_splitX_train, X_test, y_train,y_test = train_test_split(X, Y, test_size = 0.2, random_state = 0)from sklearn.linear_model import LinearRegressionregressor = LinearRegression()regressor.fit(X_train, y_train)y_pred = regressor.predict(X_test)fig = plt.figure()ax = fig.add_subplot(111, projection='3d')ax.scatter(X.iloc[:, 0], X.iloc[:, 1], Y)ax.plot(X.iloc[:, 0], X.iloc[:, 1], y_pred, color='red')ax.set_xlabel('Annual Income (k$)')ax.set_ylabel('Age')ax.set_zlabel('Spending Score')plt.show()

编辑:enter image description here

编辑2:enter image description here


回答:

绘图命令应该是:

ax.plot(X_test.iloc[:, 0], X_test.iloc[:, 1], y_pred, color='red')

因为 y_pred 仅包含 X_test 子集的 y 值,而不是整个输入 X 的 y 值。

使用连接线进行绘图(ax.plot)没有意义,因为输入数据可能没有按有意义的方式排序,即便输入数据是有序的,测试集也肯定不是有序的。

我会这样绘图:

enter image description here

from sklearn.model_selection import train_test_splitfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np# 生成一些示例数据np.random.seed(1)n = 20X = pd.DataFrame(np.random.uniform(size=(n, 2)), columns=['foo', 'bar'])Y = X['foo'] + 2*X['bar'] + np.random.normal(scale=0.2, size=n)X_train, X_test, y_train,y_test = train_test_split(X, Y, test_size = 0.2, random_state = 0)from sklearn.linear_model import LinearRegressionregressor = LinearRegression()regressor.fit(X_train, y_train)y_pred = regressor.predict(X_test)fig = plt.figure()ax = fig.add_subplot(111, projection='3d')ax.scatter(X['foo'], X['bar'], Y, label='data')for x0, x1, yt, yp in zip(X_test['foo'], X_test['bar'], y_test, y_pred):    ax.plot([x0, x0], [x1, x1], [yt, yp], color='red')ax.scatter(X_test['foo'], X_test['bar'], y_pred, color='red', marker='s', label='prediction') ax.set_xlabel('X0')ax.set_ylabel('X1')ax.set_zlabel('y')ax.legend()fig.show()

还有其他可视化的方法。你可以使用 np.meshgrid 生成网格上的 X 值,并从你的预测器获取 y 值,然后使用 plot_wireframe 绘制,并使用垂直线绘制训练和测试数据以指示它们与网格的垂直距离。具体使用哪种方法取决于数据的性质。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注