【问题标题】:Multiple Linear Regression - TypeError: fit() missing 1 required positional argument: 'y' [duplicate]多元线性回归-TypeError:fit()缺少1个必需的位置参数:'y'[重复]
【发布时间】:2020-08-31 21:45:36
【问题描述】:
import pandas as pd
from sklearn.linear_model import LinearRegression as lm

x = data_all[combi_list[0][1:]]
y = data_all[combi_list[0][0]]

lm.fit(x, y)

我正在尝试创建一个多元线性回归模型,其中包含 2 个自变量“x”和 1 个因变量“y”。

似乎无法理解为什么这个错误TypeError: fit() missing 1 required positional argument: 'y' 不断出现。

数据类型

  1. type(data_all) = pandas DataFrame
  2. type(combi_list) = 包含列表的列表

我尝试遵循类似的有效代码。 https://datatofish.com/multiple-linear-regression-python/

import pandas as pd
from sklearn import linear_model
import statsmodels.api as sm

Stock_Market = {'Year': [2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016],
                'Month': [12, 11,10,9,8,7,6,5,4,3,2,1,12,11,10,9,8,7,6,5,4,3,2,1],
                'Interest_Rate': [2.75,2.5,2.5,2.5,2.5,2.5,2.5,2.25,2.25,2.25,2,2,2,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75],
                'Unemployment_Rate': [5.3,5.3,5.3,5.3,5.4,5.6,5.5,5.5,5.5,5.6,5.7,5.9,6,5.9,5.8,6.1,6.2,6.1,6.1,6.1,5.9,6.2,6.2,6.1],
                'Stock_Index_Price': [1464,1394,1357,1293,1256,1254,1234,1195,1159,1167,1130,1075,1047,965,943,958,971,949,884,866,876,822,704,719]        
                }

df = pd.DataFrame(Stock_Market,columns=['Year','Month','Interest_Rate','Unemployment_Rate','Stock_Index_Price'])

X = df[['Interest_Rate','Unemployment_Rate']] # here we have 2 variables for multiple regression. If you just want to use one variable for simple linear regression, then use X = df['Interest_Rate'] for example.Alternatively, you may add additional variables within the brackets
Y = df['Stock_Index_Price']
 
# Correct up to here

# with sklearn
regr = linear_model.LinearRegression()
regr.fit(X, Y)

print('Intercept: \n', regr.intercept_)
print('Coefficients: \n', regr.coef_)

提前致谢!

【问题讨论】:

  • 此代码是否会导致该错误?在代码中,你有Xyregr.fit(X, Y),应该没问题
  • 是的,我写的代码抛出了 TypeError。两个代码相似,我是否遗漏了什么导致代码失败?
  • 试图运行它,对我来说很好@tom

标签: python pandas dataframe scikit-learn


【解决方案1】:

在您的代码中

from sklearn.linear_model import LinearRegression as lm

x = data_all[combi_list[0][1:]]
y = data_all[combi_list[0][0]]

lm.fit(x, y)

您尚未实例化sklearn.linear_model.LinearRegression class,但您正在使用实例方法.fit()。调用.fit()之前需要先实例化对象。

from sklearn.linear_model import LinearRegression

x = data_all[combi_list[0][1:]]
y = data_all[combi_list[0][0]]

lm = LinearRegression()
lm.fit(x, y)

来自an answer to a related question

你会得到y 丢失的看似奇怪的错误,因为.fit 是一个实例方法,所以这个函数的第一个参数实际上是self。当您在实例上调用 .fit 时,self 会自动传递。如果您在类(而不是实例)上调用.fit,则必须提供self

【讨论】:

  • 感谢您为我指明正确的方向@jakub
  • 我很高兴,@Tom。如果这回答了您的问题,请单击绿色复选标记将其标记为答案。
猜你喜欢
  • 2020-07-25
  • 1970-01-01
  • 2019-02-04
  • 1970-01-01
  • 1970-01-01
  • 2021-04-28
  • 2020-04-24
  • 2019-03-08
相关资源
最近更新 更多