简体   繁体   中英

statsmodels.api OLS function not producing output

I'm trying to accumulate a graphing function and a regression function, one from statsmodels.api and another from plotly express into a single function. At the moment this is what I have.

def lineareg(df, y, x, log, constant, plot):
    if constant == True:
        x2 = sm.add_constant(x)
        return x2
    if log == True:
        y = np.log(y)
        return y
    model = sm.OLS(y, x2, missing='drop').fit()
    if plot == True:
        fig = px.scatter(df, x=x, y=y, trendline='ols')
        fig.show()
    return model.summary()

While there is no errors in the function when I call it, it also doesn't produce any output, this is my calling function

if __name__ == '__main__':
    df = ingest('Smoking.csv')
    print(lineareg(df, y=df['bwght'], x=df['cigtax'], log=True, constant=True, plot=True))

Ingest here is just a simple function which combines the pd.read_csv() and the pd.read_excel() functions which isn't having any issues.

You used return inside the if statement, when it's actually meant to only transform the values.

So it should be:

def lineareg(df, y, x, log, constant, plot):
    if constant == True:
        x2 = sm.add_constant(x)
    if log == True:
        y = np.log(y)
    model = sm.OLS(y, x2, missing='drop').fit()
    if plot == True:
        fig = px.scatter(df, x=x, y=y, trendline='ols')
        fig.show()
    return model.summary()


df = pd.DataFrame({'bwght':np.random.uniform(0,1,100),
                   'cigtax':np.random.uniform(0,1,100)})
lineareg(df, y=df['bwght'], x=df['cigtax'], log=True, constant=True, plot=True)

Works for me:

在此处输入图片说明

OLS Regression Results
Dep. Variable:  bwght   R-squared:  0.001
Model:  OLS Adj. R-squared: -0.009
Method: Least Squares   F-statistic:    0.08564
Date:   Sat, 21 Nov 2020    Prob (F-statistic): 0.770
Time:   13:59:44    Log-Likelihood: -147.27
No. Observations:   100 AIC:    298.5
Df Residuals:   98  BIC:    303.8
Df Model:   1       
Covariance Type:    nonrobust       
coef    std err t   P>|t|   [0.025  0.975]
const   -1.1543 0.211   -5.475  0.000   -1.573  -0.736
cigtax  0.1084  0.370   0.293   0.770   -0.627  0.843
Omnibus:    32.671  Durbin-Watson:  2.285
Prob(Omnibus):  0.000   Jarque-Bera (JB):   52.573
Skew:   -1.468  Prob(JB):   3.84e-12
Kurtosis:   5.001   Cond. No.   4.37

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM