Generalized Additive Models (GAMs) are a flexible class of statistical models that extend traditional linear regression by allowing non-linear relationships between predictors and the response variable. Instead of assuming straight-line relationships, GAMs use smooth functions called splines that can capture complex patterns in the data.
This flexibility makes GAMs particularly useful for modeling real-world phenomena where relationships may be curved, seasonal, or otherwise non-linear. For example, the relationship between temperature and energy consumption often follows a U-shape that would be poorly captured by linear regression.
While GAMs are powerful and flexible, their estimated parameters can be difficult to interpret directly since they involve complex spline basis functions. Fortunately, the marginaleffects package provides tools to understand and visualize GAM results using the same intuitive workflow as simpler models - through predictions, counterfactual comparisons, and slopes.
19.1 Estimation
We will estimate a GAM model using the mgcv package and the simdat dataset distributed with the itsadug package:
Compute adjusted predictions for each observed combination of regressor in the dataset used to fit the model. This gives us a dataset with the same number of rows as the original data, but new columns with predicted values and uncertainty estimates:
Marginal effects are slopes of the prediction equation. They are an observation-level quantity. The slopes() function produces a dataset with the same number of rows as the original data, but with new columns for the slop and uncertainty estimates:
We can plot marginal effects for different values of a regressor using the plot_slopes() function. This next plot shows the slope of the prediction equation, that is, the slope of the previous plot, at every value of the Time variable.
The marginal effects in this plot can be interpreted as measuring the change in Y that is associated with a small increase in Time, for different baseline values of Time.
19.4 Excluding terms
The predict() method of the mgcv package allows users to “exclude” some smoothing terms, using the exclude argument. You can pass the same argument to any function in the marginaleffects package:
Estimate Std. Error z Pr(>|z|) S 2.5 % 97.5 %
11.7 0.695 16.9 <0.001 210.8 10.4 13.1
Type: response
See the documentation in ?mgcv:::predict.bam for details.
19.5 Warning
It may not always be appropriate to compute aggregated (aka, average or marginal) for models with splines. See Wood (2017) for a technical reference and this Cross Validated post for a discussion.
Wood, Simon N. 2017. Generalized Additive Models: An Introduction with r. 2nd ed. Boca Raton, FL: Chapman; Hall/CRC.