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

Vio*_*997 3 python machine-learning scikit-learn

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

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
Run Code Online (Sandbox Code Playgroud)

和“价格”:

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
Run Code Online (Sandbox Code Playgroud)

使用以下代码:

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_)
Run Code Online (Sandbox Code Playgroud)

但是,截距和斜率系数打印命令给了我以下输出:

[[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.]]
Run Code Online (Sandbox Code Playgroud)

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

iz_*_*iz_ 8

从本质上讲,是什么导致了奇怪的看着coef_,并intercept_为您的数据有205层的功能和只用1个样本205个目标的事实。绝对不是你想要的!

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

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_)
Run Code Online (Sandbox Code Playgroud)

我使用那里的数组进行测试,但显然使用数据帧中的数据。

PS 如果省略调整大小,则会收到如下错误消息:

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.
Run Code Online (Sandbox Code Playgroud)

^ 它会告诉你该怎么做!