import warnings
import numpy as np
import pandas as pd
import statsmodels.api as sm
from plotnine import (
aes,
geom_line,
geom_point,
geom_vline,
ggplot,
labs,
theme_bw,
)
from plotnine.data import mtcars
from scipy.interpolate import make_smoothing_spline
from scipy.special import expit
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import KFold
from statsmodels.gam.api import BSplines, GLMGam
warnings.filterwarnings("ignore")
rng = np.random.default_rng(123)
def simulate_polynomial_data(rng, n=1000, x_sd=0.25, error_sd=0.5):
"""Simulate the polynomial relationship used throughout the slides."""
x = rng.normal(loc=0, scale=x_sd, size=n)
y = (
1
+ 5.3 * x
- 45 * x**2
- 35.5 * x**3
+ 60 * x**4
+ rng.normal(loc=0, scale=error_sd, size=n)
)
return pd.DataFrame({"x": x, "y": y})
# Data for the motivating examples
polynomial_plot_data = simulate_polynomial_data(rng)
x_sine = rng.normal(loc=0, scale=3.5, size=1000)
y_sine = 1 + np.sin(np.pi * x_sine / 8) + rng.normal(
loc=0,
scale=0.25,
size=1000,
)
sinusoidal_plot_data = pd.DataFrame({"x": x_sine, "y": y_sine})
# Separate simulated datasets for the spline and local-regression examples
spline_example_data = simulate_polynomial_data(rng)
# Data for the GAM examples
mtcars_data = mtcars.copy()
x_gam = rng.normal(loc=0, scale=1, size=1000)
y_gam = rng.normal(loc=4, scale=1, size=1000)
mu_gam = np.exp(-2 + expit(x_gam) + np.sqrt(y_gam + 15))
z_gam = rng.poisson(mu_gam)
poisson_gam_data = pd.DataFrame(
{"x": x_gam, "y": y_gam, "mu": mu_gam, "z": z_gam}
)