为什么无需重新调整一维数组的形状以适合具有多个变量的线性回归

问题描述 投票:0回答:1

在sklearn中,为了在线性回归中使用fit方法训练数据,我们必须重塑1D数组的形状。但是,在具有多个变量的线性回归的情况下,我得到的输出没有更改目标变量的形状。

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个回答
0
投票

请看这个例子

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,)

如果尝试使用X和y拟合模型。.即使y形状为(4,),也不会出现错误。这是因为X的形状为(4,2)。所以sklearn如有必要,会将您的目标强制转换为X的dtype。

如果尝试拟合Xr和y。两者都是一列0列的一维数组。 [您将得到错误的信息,表示期望的2D数组,而改为1D数组:。在这种情况下,至少您的Xr训练数据应该是具有1列的1D数组。然后sklearn将通过投射目标来为您完成其余工作Xr形状。

read more about fit method and what it does here

© www.soinside.com 2019 - 2024. All rights reserved.