如何使用scikitlearn在Python中打印简单线性回归的截距和斜率?

2024-05-14 03:43:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用一个简单的线性回归(只有一个自变量)预测汽车价格(通过机器学习)。变量为“每加仑公路里程”

0      27
1      27
2      26
3      30
4      22
       ..
200    28
201    25
202    23
203    27
204    25
Name: highway-mpg, Length: 205, dtype: int64

和“价格”:

0      13495.0
1      16500.0
2      16500.0
3      13950.0
4      17450.0
        ...   
200    16845.0
201    19045.0
202    21485.0
203    22470.0
204    22625.0
Name: price, Length: 205, dtype: float64

使用以下代码:

from sklearn.linear_model import LinearRegression

x = df["highway-mpg"]
y = df["price"]
lm = LinearRegression()

lm.fit([x],[y])
Yhat = lm.predict([x])

print(Yhat)
print(lm.intercept_)
print(lm.coef_)

但是,intercept和slope coefficient print命令提供以下输出:

[[0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 ...
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]]

为什么不打印截距和斜率系数?“Yhat”打印命令确实正确地打印出数组中的预测值,但不知何故,其他打印命令没有打印出我想要的输出


Tags: name命令df价格lengthpricelmprint
1条回答
网友
1楼 · 发布于 2024-05-14 03:43:37

从本质上说,造成这种奇怪的coef_intercept_的原因是,您的数据只有一个样本,有205个特征和205个目标。绝对不是你想要的

您可能需要一个特性、205个样本和一个目标。为此,您需要重塑数据:

from sklearn.linear_model import LinearRegression
import numpy as np

mpg = np.array([27, 27, 26, 30, 22, 28, 25, 23, 27, 25]).reshape(-1, 1)
price = np.array([13495.0, 16500.0, 16500.0, 13950.0, 17450.0, 16845.0, 19045.0, 21485.0, 22470.0, 22625.0])

lm = LinearRegression()
lm.fit(mpg, price)

print(lm.intercept_)
print(lm.coef_)

我使用了那里的阵列进行测试,但显然使用了数据帧中的数据

注意:如果忽略调整大小,则会出现如下错误消息:

ValueError: Expected 2D array, got 1D array instead:
array=[27 27 26 30 22 28 25 23 27 25].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

^它告诉你该怎么做

相关问题 更多 >