Statistical modeling with Python · Lesson 1 of 16
Statistical modeling in Python: the toolbox
Meet statsmodels, SciPy and scikit-learn, fit your first regression in five lines, and learn when to use formulas and when arrays.
A statistical model is a short description of how one thing depends on others, plus an honest measure of how sure we can be. "Each extra hour of study adds about 3 points to the exam score, give or take 1" is a model. So is "customers who visit the site often are more likely to buy".
Python has three libraries for this work. You will use all three in this course, and they all run in your browser on this page (the first run takes a few seconds while they load).
- statsmodels: classic statistics. Regression, logistic regression and other GLMs, with standard errors, p-values and confidence intervals. Best when you want to explain and test.
- SciPy (
scipy.stats): probability distributions and the classic tests (t-test, chi-square, correlation). - scikit-learn: machine learning. Same models, but built to predict on new data: train/test splits, cross-validation, scores.
Your first model in five lines
Ten students wrote down how many hours they studied and their score. The formula API of statsmodels (smf) lets you write the model the way you would say it: score ~ hours, "score depends on hours".
import pandas as pd
df = pd.DataFrame({
"hours": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
"score": [48, 50, 57, 55, 62, 66, 64, 73, 75, 80],
})
import statsmodels.formula.api as smf
model = smf.ols("score ~ hours", data=df).fit()
print(model.params.round(2))
print("R-squared:", round(model.rsquared, 3))Intercept 43.87 hours 3.48 dtype: float64 R-squared: 0.962
ols = ordinary least squares, the classic straight-line fit.
How to read it: Intercept is the predicted score for 0 hours (about 44). The number next to hours is the slope: each extra hour goes with about 3.5 more points. R-squared is the share of the differences between students that the line explains: 0.96 is very high, because this example data is tidy. Real data rarely is.
Formulas or arrays
statsmodels has a second way in: give it the numbers as arrays. Then you must add the intercept column yourself with sm.add_constant. The answer is the same; only the names change (const instead of Intercept).
import pandas as pd
df = pd.DataFrame({
"hours": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
"score": [48, 50, 57, 55, 62, 66, 64, 73, 75, 80],
})
import statsmodels.api as sm
X = sm.add_constant(df[["hours"]])
model = sm.OLS(df["score"], X).fit()
print(model.params.round(2))const 43.87 hours 3.48 dtype: float64
Formulas are shorter and handle text columns for you (you will see C(...) for categories later), so this course mostly uses them. scikit-learn always takes arrays: a table of inputs X and a column y.
import pandas as pd
df = pd.DataFrame({
"hours": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
"score": [48, 50, 57, 55, 62, 66, 64, 73, 75, 80],
})
from sklearn.linear_model import LinearRegression
reg = LinearRegression().fit(df[["hours"]], df["score"])
print("intercept:", round(float(reg.intercept_), 2))
print("slope:", round(float(reg.coef_[0]), 2))
new = pd.DataFrame({"hours": [5.5, 12]})
print(reg.predict(new).round(1))intercept: 43.87 slope: 3.48 [63. 85.6]
Same line, found by scikit-learn. predict() gives the score for new hours.
scikit-learn gives the same line but no p-values and no confidence intervals: it is built for prediction. statsmodels gives the full statistical report. On your own computer, that report is one call:
print(model.summary())A full regression report: coefficients, standard errors, p-values, R-squared and more.
The summary is a wide text table with the date and the library version in it. In this course we print only the parts we need (params, pvalues, conf_int(), rsquared), rounded, and each lesson explains how to read them.
✎ Exercise
A garden centre measured how much water (litres per week) eight plants got and how much they grew (cm). Fit growth ~ water with smf.ols and print the coefficients rounded to 2 decimals.
Hint: smf.ols("growth ~ water", data=plants).fit(), then print(model.params.round(2)).
import pandas as pd
import statsmodels.formula.api as smf
plants = pd.DataFrame({
"water": [1, 2, 2, 3, 4, 4, 5, 6],
"growth": [3.1, 4.0, 4.6, 5.2, 6.1, 6.5, 7.0, 8.2],
})
# your code here
Expected output:
Intercept 2.25 water 0.99 dtype: float64
Show a solution
import pandas as pd
import statsmodels.formula.api as smf
plants = pd.DataFrame({
"water": [1, 2, 2, 3, 4, 4, 5, 6],
"growth": [3.1, 4.0, 4.6, 5.2, 6.1, 6.5, 7.0, 8.2],
})
model = smf.ols("growth ~ water", data=plants).fit()
print(model.params.round(2))Intercept 2.25 water 0.99 dtype: float64
Check yourself
1. In smf.ols("score ~ hours", data=df), what does ~ mean?
The tilde separates the outcome (left) from the predictors (right).
2. Which library would you pick to get p-values and confidence intervals for a regression?
statsmodels reports standard errors, p-values and intervals; scikit-learn focuses on prediction.
3. With sm.OLS(y, X) (arrays, no formula), what must you add yourself?
The array API fits exactly the columns you give it; without a constant the line is forced through 0.