【问题标题】:Why there is no need to reshaping of 1D array to fit in linear regression with multiple variables为什么不需要重塑一维数组以适应具有多个变量的线性回归
【发布时间】:2020-03-11 11:27:26
【问题描述】:

在 sklearn 中,为了在线性回归中使用 fit 方法训练数据,我们必须重塑一维数组。但是,在具有多个变量的线性回归的情况下,我得到了输出而没有对目标变量进行整形。

import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression

df = pd.read_csv("Weather.csv",low_memory = False) # the data set I used
df1 = df[["Precip","MaxTemp"]]

reg = LinearRegression().fit(df1.head(),df.MinTemp.head()) # no error with shape of df1 is (5,2) and shape of df.MinTemp.head() is (5,)

我能知道这背后的原因吗?提前致谢。

【问题讨论】:

标签: python machine-learning linear-regression


【解决方案1】:

请看这个例子

from sklearn.linear_model import LinearRegression
import numpy as np

Xr = np.random.randint(0,10,4) # random 1D array with 0 columns -> shape is (4,)

X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]]) # random array which shape is (4,2)
y = np.dot(X, np.array([1, 2])) + 3 # 1D array  with 0 columns -> shape is (4,)

regr = LinearRegression()
# regr.fit(Xr,y) this would raise an exception
regr.fit(X,y)
regr.predict(X) # returns array([ 6.,  8.,  9., 11.])

如果您尝试使用 X 和 y 来拟合模型。即使 y 形状为 (4,),您也不会出错。这是因为您的 X 的形状为 (4,2 ).so sklearn 会在必要时将您的目标转换为 X 的 dtype。

如果您尝试拟合 Xr 和 y。两者都是 0 列的一维数组。 你会得到错误说 Expected 2D array, got 1D array instead:。在这种情况下,至少你的 Xr 训练数据应该是一个 1 列的 1D 数组。然后 sklearn 将通过转换为你完成剩下的工作目标看着 Xr 形状。

read more about fit method and what it does here

【讨论】:

    猜你喜欢
    • 2019-06-09
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    相关资源
    最近更新 更多