【问题标题】:Python: Function for Multiple RegressionPython:多重回归函数
【发布时间】:2022-07-27 22:40:28
【问题描述】:

我有以下数据框:

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\'])

目前,我可以使用以下函数对 \'Stock_Index_Price\' 执行 \'Interest_Rate\' 和 \'Unemployment_Rate\' 的多元回归:

def perform_regression_multiple(y, x1, x2=\"\"):
    test = df[[y, x1, x2]].reset_index(drop=True)
    
    X = test[[x1, x2]]
    Y = test[[y]]
    
    regr = linear_model.LinearRegression()
    regr.fit(X, Y)

    model = sm.OLS(Y, X).fit()
    predictions = model.predict(X) 

    print_model = model.summary()
    print(print_model)
    
#===========================================================================

perform_regression_multiple(\'Stock_Index_Price\', \'Interest_Rate\', \'Unemployment_Rate\')

但是,当我尝试使用上述函数执行线性回归(例如,使用 \'Interest_Rate\' 作为唯一解释变量)时,我会收到以下错误消息:

perform_regression_multiple(\'Stock_Index_Price\', \'Interest_Rate\')

KeyError: \"[\'\'] 不在索引中\"

显然,x1 和 x2 都需要指定;否则它将无法正常工作。我应该如何以允许我指定解释变量数量的方式修改函数?目标是通过其他因素扩展回归模型。

非常感谢您的任何建议!

    标签: python pandas function linear-regression statsmodels


    【解决方案1】:

    看看你是如何定义你的函数的:

    def perform_regression_multiple(y, x1, x2=""):
    

    然后你怎么称呼它:

    perform_regression_multiple('Stock_Index_Price', 'Interest_Rate')
    

    通过该调用,您将告诉函数y="Stock Index Price"x1="Interest Rate"x2="",这是默认值。

    在函数的第一行,您将使用 x2 列:

    test = df[[y, x1, x2]].reset_index(drop=True)
    

    您已定义为“”,错误是说名称为“”的列不存在。

    如果您希望能够使用一个或两个变量执行回归,请执行以下操作:

    def perform_regression_multiple(y, x1, x2=None):
        if x2:
            test = df[[y, x1, x2]].reset_index(drop=True)
        
            X = test[[x1, x2]]
        else:
            test = df[[y, x1]].reset_index(drop=True)
            
            X = test[[x1]]
        Y = test[[y]]
        
        regr = linear_model.LinearRegression()
        regr.fit(X, Y)
    
        model = sm.OLS(Y, X).fit()
        predictions = model.predict(X) 
    
        print_model = model.summary()
        print(print_model)
    

    您也可以保留空字符串,if 仍然会以相同的方式工作。

    更好的是,考虑到要在 pandas 中选择列并返回数据框,您必须传递一个列表,您可以这样做,将一个列表传递给 x_variables 参数(即使它只是一个项目的列表):

    def perform_regression_multiple(y: str, x_variables: list):
            columns = [y] + x_variables
            test = df[columns].reset_index(drop=True)
                
            X = test[x_variables]
            Y = test[[y]]
            
            regr = linear_model.LinearRegression()
            regr.fit(X, Y)
        
            model = sm.OLS(Y, X).fit()
            predictions = model.predict(X) 
        
            print_model = model.summary()
            print(print_model)
    

    【讨论】:

    • 谢谢哈维尔,对我来说就像一个魅力!另一个问题:假设我有 8 个解释变量(即 x1、x2、x3、....、x8)。有没有办法以与上述相同的“短”方式声明条件,而不必为每个变量指定“if”命令?
    • 用解决方案编辑
    • 很棒的东西,刚刚学到了一些新东西。再次感谢哈维尔 - 祝你有个美好的未来:)
    猜你喜欢
    • 2020-08-24
    • 1970-01-01
    • 2017-06-19
    • 2021-07-18
    • 1970-01-01
    • 2022-08-13
    • 2014-05-04
    • 2016-06-30
    • 1970-01-01
    相关资源
    最近更新 更多