from pathlib import Path
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import lapylace as lp
sys.path.append(str(Path.cwd().parent / 'python'))
from data import ros_pathStudent
Models for regression coefficients. See Chapter 12 in Regression and Other Stories.
Source: Student/student.Rmd.
The Python version keeps data handling explicit and uses lapylace for Stan-backed generalized linear models, so the statistical model can be read from a formula rather than from handwritten Stan.
Data
student_merged = pd.read_csv(ros_path('Student/data', 'student-merged.csv'))
student_merged.head()| G1mat | G2mat | G3mat | G1por | G2por | G3por | school | sex | age | address | ... | higher | internet | romantic | famrel | freetime | goout | Dalc | Walc | health | absences | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 7 | 10 | 10 | 13 | 13 | 13 | 0 | 0 | 15 | 0 | ... | 1 | 1 | 0 | 3 | 1 | 2 | 1 | 1 | 1 | 2 |
| 1 | 8 | 6 | 5 | 13 | 11 | 11 | 0 | 0 | 15 | 0 | ... | 1 | 1 | 1 | 3 | 3 | 4 | 2 | 4 | 5 | 2 |
| 2 | 14 | 13 | 13 | 14 | 13 | 12 | 0 | 0 | 15 | 0 | ... | 1 | 0 | 0 | 4 | 3 | 1 | 1 | 1 | 2 | 8 |
| 3 | 10 | 9 | 8 | 10 | 11 | 10 | 0 | 0 | 15 | 0 | ... | 1 | 1 | 0 | 4 | 3 | 2 | 1 | 1 | 5 | 2 |
| 4 | 10 | 10 | 10 | 13 | 13 | 13 | 0 | 0 | 15 | 0 | ... | 1 | 1 | 1 | 4 | 2 | 1 | 2 | 3 | 3 | 8 |
5 rows × 32 columns
Models
The formulas below are the Python counterparts of the model formulas in the source example. Use lapylace for the Stan-backed Bayesian fit with the same formula interface.
# fit = lp.stan_glm('G3mat ~ _', data=student_merged, family=lp.gaussian(), chains=4, iter_sampling=1000)
# fit = lp.stan_glm('G3mat ~ _', data=student_merged, family=lp.gaussian(), chains=4, iter_sampling=1000)
# fit = lp.stan_glm('G3mat ~ _', data=student_merged, family=lp.gaussian(), chains=4, iter_sampling=1000)
# fit = lp.stan_glm('G3mat ~ _', data=student_merged, family=lp.gaussian(), chains=4, iter_sampling=1000)
# fit = lp.stan_glm('G3mat ~ failures + schoolsup + goout + absences', data=student_merged, family=lp.gaussian(), chains=4, iter_sampling=1000)Notes
- Source computation blocks represented: 41.
- Data paths are expressed through the shared
ros_path()helper. - Formula-based Bayesian regressions are routed through
lapylace.stan_glm(). - Plotting and simulation work uses NumPy, pandas, matplotlib idioms.