As observed in our initial visualization, penguins cluster by species. Instead of one global model, we can fit individual regressions for each species.
1. Species-Specific Training
We split the data and train three distinct models for Adelie, Chinstrap, and Gentoo penguins.
# Get the name of each speciesspecies_list = penguins['species'].unique()models = {}# For each species, fit a separate linear regression modelfor species in species_list:# Select the subset of data for the current species subset = penguins[penguins['species'] == species] X_s = subset[["bill_length_mm"]] y_s = subset["body_mass_g"]# Fit the model model_s = LinearRegression().fit(X_s, y_s) models[species] = model_s# Print the R^2 score for each species-specific modelprint(f"{species} R^2 Score: {model_s.score(X_s, y_s):.3f}")
Visualizing separate lines highlights the different relationships between bill length and body mass across species.
# Visualize the regression lines for all speciessns.lmplot(data=penguins, x="bill_length_mm", y="body_mass_g", hue="species")plt.title("Linear Regression per Species")
Text(0.5, 1.0, 'Linear Regression per Species')
By analyzing each separately, we capture the unique biological traits of each group.