import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from plotnine import (
aes,
geom_line,
geom_point,
ggplot,
labs,
scale_x_continuous,
theme_bw,
)
from plotnine.data import penguins
from sklearn.model_selection import KFold, cross_val_score
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor, plot_tree
RANDOM_STATE = 123
# Load and clean the Palmer Penguins data.
df = penguins.dropna().copy().reset_index(drop=True)
# Define the predictors and outcomes used throughout the presentation.
regression_features = [
"flipper_length_mm",
"bill_length_mm",
"bill_depth_mm",
]
classification_features = [
"body_mass_g",
"flipper_length_mm",
"bill_length_mm",
"bill_depth_mm",
]
X_regression = df[regression_features]
y_regression = df["body_mass_g"]
X_classification = df[classification_features]
y_classification = df["species"]
# Reproduce the original 50% training sample for both models.
rng = np.random.default_rng(RANDOM_STATE)
train_index = np.sort(
rng.choice(df.index, size=len(df) // 2, replace=False)
)
X_regression_train = X_regression.loc[train_index]
y_regression_train = y_regression.loc[train_index]
X_classification_train = X_classification.loc[train_index]
y_classification_train = y_classification.loc[train_index]
# Ten-fold cross-validation used in the pruning section.
cv = KFold(n_splits=10, shuffle=True, random_state=RANDOM_STATE)