数值错误:x和y必须具有相同的第一维度,但形状分别为(10, 1)和(90,)。

3

我正在Udemy学习机器学习。在多项式回归的一堂课中,以下代码如下:

# importing libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# importing dataset
dataset = pd.read_csv("Position_Salaries.csv")
x = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2].values
print(x.shape)
print(y.shape)
# fitting LR to the dataset
from sklearn.linear_model import LinearRegression
linreg = LinearRegression()
linreg.fit(x, y)

# fitting PR to the dataset
from sklearn.preprocessing import PolynomialFeatures
polreg = PolynomialFeatures(degree=2)
x_poly = polreg.fit_transform(x)
linreg2 = LinearRegression()
linreg2.fit(x_poly, y)


# visualising the polynomial regression results
x_grid = np.arange(min(x), max(x), 0.1)
x_grid = x_grid.reshape((len(x_grid), 1))
plt.scatter(x, y, color = "red")
plt.plot(x, linreg2.predict(polreg.fit_transform(x_grid)), color = "blue" )
plt.title("Truth or Bluff PR")
plt.xlabel("Position")
plt.ylabel("Salary")
plt.show()

我收到了以下错误信息:
Traceback (most recent call last):
  File "/home/ashutosh/Machine Learning A-Z Template Folder/Part 2 - Regression/Section 6 - Polynomial Regression/P14-Polynomial-Regression/Polynomial_Regression/plr.py", line 29, in <module>
    plt.plot(x, linreg2.predict(polreg.fit_transform(x_grid)), color = "blue" )
  File "/usr/local/lib/python3.7/dist-packages/matplotlib/pyplot.py", line 2795, in plot
    is not None else {}), **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/matplotlib/axes/_axes.py", line 1666, in plot
    lines = [*self._get_lines(*args, data=data, **kwargs)]
  File "/usr/local/lib/python3.7/dist-packages/matplotlib/axes/_base.py", line 225, in __call__
    yield from self._plot_args(this, kwargs)
  File "/usr/local/lib/python3.7/dist-packages/matplotlib/axes/_base.py", line 391, in _plot_args
    x, y = self._xy_from_xy(x, y)
  File "/usr/local/lib/python3.7/dist-packages/matplotlib/axes/_base.py", line 270, in _xy_from_xy
    "have shapes {} and {}".format(x.shape, y.shape))
ValueError: x and y must have same first dimension, but have shapes (10, 1) and (90,)

数据集可以从这里下载:https://sds-platform-private.s3-us-east-2.amazonaws.com/uploads/P14-Polynomial-Regression.zip

我能做什么?


我的第一步将是将 linreg2.predict(polreg.fit_transform(x_grid)) 从绘图函数中取出并作为自己的变量进行调查。它的形状是否符合您的预期?它是否包含您期望包含的值? - G. Anderson
“plot”认为2个输入数组(“x”,“y”)的形状不兼容。对于普通图,应该有一个“y”值与“x”变量的每个值相对应。如何将90个值绘制在10个值上? - hpaulj
1
你已经使用 print(x.shape) 打印出了 x 的形状。那个图的 y 值是通过使用 x_grid 进行 fit_transform 生成的,而 x_grid 可能有 90 个元素?无论如何,你可以测试和纠正数组大小,我们不能。 - hpaulj
@hpaulj 数据集中的 x 和 y 具有相同的形状。 - Ashutosh Dash
我指的不是原始的 y,而是您传递给 plot 的第二个参数。 - hpaulj
我已经得到了答案,在第29行中,我应该写x_grid而不是x。 - Ashutosh Dash
1个回答

0
在第29行中,将x替换为x_grid,即:从

plt.plot(x, linreg2.predict(polreg.fit_transform(x_grid)), color = "blue" )

plt.plot(x_grid, linreg2.predict(polreg.fit_transform(x_grid)), color = "blue" )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接