Implementation of Generalized additive model in Python
Step 1: Install the pyGAM
library
First, ensure you have the pyGAM
library installed. You can install it using pip:
pip install pygam
Step 2: Import necessary libraries
Import pyGAM
and other required libraries like numpy
and pandas
for data manipulation:
import numpy as np
import pandas as pd
from pygam import LinearGAM, s
Step 3: Prepare your data
Load and prepare your dataset. For demonstration, let’s use a sample dataset:
# Example dataset
np.random.seed(0)
X = np.random.rand(100, 1) * 10 # 100 data points, 1 feature
y = np.sin(X).ravel() + np.random.normal(0, 0.5, 100) # target variable with some noise
Step 4: Define and fit the GAM
Create a GAM model using the LinearGAM
class and specify the smoothing term using the s
function. Fit the model to your data:
# Define the GAM model
gam = LinearGAM(s(0))
# Fit the model to the data
gam.fit(X, y)
Step 5: Evaluate the model
Evaluate the model by checking its performance metrics and visualizing the results:
# Predict on new data
X_pred = np.linspace(0, 10, 500).reshape(-1, 1)
y_pred = gam.predict(X_pred)
# Plot the results
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6))
plt.scatter(X, y, label='Data', alpha=0.5)
plt.plot(X_pred, y_pred, label='GAM Prediction', color='red')
plt.xlabel('X')
plt.ylabel('y')
plt.legend()
plt.show()
Output:
Generalized additive model in Python
Generalized additivemodels Models are a wider and more flexible form of a linear model with nonparametric terms and are simply extensions of generalized linear models. Whereas simple linear models are useful when relationships between two variables are strikingly linear, all of which might not be possible in the real world, generalized additive models are advantageous in that they can simultaneously capture non-linear relationships between two variables. In