python-3.x - PyPlot 错误“X 和 Y 的大小必须相同”,我在网上找到的所有内容都不起作用
问题描述
我正在尝试在 Scikit-Learn 中创建一个线性回归模型。虽然我遇到了问题。就是说 x 和 y 的大小不同。我正在使用谷歌的“加州住房”数据集。这是代码:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
dataset = pd.read_csv('/content/sample_data/california_housing_train.csv')
x = dataset.iloc[:, :-2].values
y = dataset.iloc[:, :-1].values
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 1/3)
from sklearn.linear_model import LinearRegression
lr = LinearRegression()
lr.fit(x_train, y_train)
y_pred = lr.predict(x_test)
plt.scatter(x_train, y_train, color = "red")
plt.plot(x_train, lr.predict(x_train), color = "green")
plt.title("Income vs Home Value (Training set)")
plt.xlabel("Income")
plt.ylabel("Home Value")
plt.show()
plt.scatter(x_test, y_test, color = "red")
plt.plot(x_train, lr.predict(x_train), color = "green")
plt.title("Income vs Home Value (Testing set)")
plt.xlabel("Income")
plt.ylabel("Home value")
plt.show()
错误:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-47-95095200e54b> in <module>()
18 y_pred = lr.predict(x_test)
19
---> 20 plt.scatter(x_train[0], y_train[:], color = "red")
21 plt.plot(x_train, lr.predict(x_train), color = "green")
22 plt.title("Income vs Home Value (Training set)")
3 frames
/usr/local/lib/python3.7/dist-packages/matplotlib/axes/_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, plotnonfinite, **kwargs)
4389 y = np.ma.ravel(y)
4390 if x.size != y.size:
-> 4391 raise ValueError("x and y must be the same size")
4392
4393 if s is None:
ValueError: x and y must be the same size
我不知道为什么。我已经尝试了其他帖子上的所有内容。根据我在其他帖子上的发现,这是因为一个(x 或 y)是 2d,一个是 1d。尽管“修复”不起作用。
解决方案
查看 x 和 y 变量的尺寸:
[ins] In [34]: x.shape
Out[34]: (17000, 7)
[ins] In [35]: y.shape
Out[35]: (17000, 8)
y 变量应该是目标变量,即房价:
y = dataset.iloc[:,-1].values
您的 x 变量定义忽略了您要绘制的 median_income,因此这是一个包含收入变量的 x 矩阵:
x = dataset.iloc[:, :-1].values
如上所述定义 y 现在是一维的;x 矩阵中有 8 个变量,其中最后一个(索引 7)是 median_income。要绘制它:
plt.scatter(x_train[:,7], y_train, color = "red")
推荐阅读
- node.js - 为具有异构数组的对象创建猫鼬模式
- javascript - 查找具有样式属性的元素并更改它
- ruby-on-rails - 在 ruby mechanize 中获取连接详细信息
- ios - 滚动 react-native 时如何防止对 textInput 的关注?
- dask - Dask.dataframe.to_parquet 制作非常大的文件
- python - Project Euler - 寻找除数问题 12
- tensorflow - raise ValueError('boxlists 的所有元素都应该是 BoxList 对象')
- nginx - rtmp模块流没有,如何解决?
- c# - 是否可以创建一个可以添加两个不同类的列表?
- powershell - 为什么分号的执行时间比逗号长 500 倍?