简体   繁体   中英

Linear Regression Coeficients in Python

I'm new in Python and I'm trying to make a linear regression with a csv and I need to obtain the coefficients but I don't know how. This is what I have tried:

import statsmodels.api as sm
x = datos1['Ozone']
y = datos1['Temp']
x = np.array(x)
y= np.array(y)
model = sm.OLS(y, x)
results = model.fit()
print(results.summary())

Could you help me? Thanks.

Try running,

import statsmodels.api as sm
x = datos1['Ozone']
y = datos1['Temp']
x = np.array(x)`enter code here`
y= np.array(y)
model = sm.OLS(y, x)
results = model.fit()

print(results.params)

For details please see: statsmodels.regression.linear_model.OLS

There are two ways to get the parameters of the OLS model.

Way 1: Use model.params

x = datos1['Ozone']
y = datos1['Temp']
x = np.array(x)
y= np.array(y)
model = sm.OLS(y, x)
results = model.fit()
print(results.params)

Way 2: Use model.summary() with pandas

x = datos1['Ozone']
y = datos1['Temp']
x = np.array(x)
y= np.array(y)
model = sm.OLS(y, x)
results = model.fit()

df = pd.read_html(results.summary().tables[1].as_html(),header=0,index_col=0)[0]
print(df.columns.values) # get parameters as dataframe 
print(df['coef']) # get coefficients

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