[英]Linear regression model shapes - ValueError: x and y must have same first dimension, but have shapes (5,) and (1, 5)
I'm following this example https://www.analyticsvidhya.com/blog/2020/03/polynomial-regression-python/我正在关注这个例子https://www.analyticsvidhya.com/blog/2020/03/polynomial-regression-python/
I am trying to fit a linear line of best fit to my matplotlib graph.我正在尝试将最适合我的 matplotlib 图的线性线拟合。 I keep getting the error that x and y do not have the same first dimension.我不断收到 x 和 y 没有相同第一维的错误。 But they both have lengths of 5?但是它们的长度都是 5? What am I doing wrong?我究竟做错了什么?
ValueError: x and y must have same first dimension, but have shapes (5,) and (1, 5) ValueError: x 和 y 必须具有相同的第一维,但具有形状 (5,) 和 (1, 5)
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.metrics import mean_squared_error
from sklearn.linear_model import LinearRegression
df = pd.read_csv('head_london_pm25vspm10.csv').dropna()
x = df['pm25_ugm3'].values
y = df['pm10'].values
# Training Model
lm = LinearRegression().fit(x.reshape(1, -1), y.reshape(1, -1))
y_pred = lm.predict(x.reshape(1, -1))
# plotting dataset
plt.figure(figsize=(10, 5))
plt.scatter(x, y, s=15)
plt.plot(x, y_pred, color='r')
plt.xlabel('pm25', fontsize=16)
plt.ylabel('pm10', fontsize=16)
plt.show()
print('RMSE for Linear Regression=>', np.sqrt(mean_squared_error(y, y_pred)))
CSV file - 'head_london_pm25vspm10.csv' CSV 文件- 'head_london_pm25vspm10.csv'
pm25_ugm3,pm10
3.8,7.9
4.1,10.5
4.2,10.5
4.5,10.9
4.7,11.2
LinearRegression works with arrays. LinearRegression 适用于数组。 As your data are only vectors you have to reshape (reshape(1, -1)) them into arrays to work with LinearRegression.由于您的数据只是向量,因此您必须将它们重塑 (reshape(1, -1)) 成数组以使用 LinearRegression。
The output of the LinearRegression is then again an array. LinearRegression 的输出又是一个数组。 But your input x
is still a vector.但是您的输入x
仍然是一个向量。 For the plot function both inputs need to have the same shape though.对于绘图函数,两个输入都需要具有相同的形状。
You can reshape the output back from LinearRegression to a vector so it matches again the shape of the x vector您可以将 LinearRegression 的输出重新整形为向量,使其再次与 x 向量的形状匹配
y_pred = lm.predict(x.reshape(1, -1)).reshape(-1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.