pythonintermediate

OLS Regression with statsmodels

Fit and interpret an Ordinary Least Squares regression model with diagnostics using statsmodels.

python
import statsmodels.api as sm
import numpy as np, pandas as pd

np.random.seed(0)
n = 200
df = pd.DataFrame({'x1': np.random.randn(n),'x2': np.random.randn(n),'y': 3 + 2*np.random.randn(n)})

X = sm.add_constant(df[['x1','x2']])
model = sm.OLS(df['y'], X).fit()
print(model.summary())
print('AIC:', model.aic)

Use Cases

  • econometric analysis
  • feature significance testing
  • predictive modeling

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.