what are AIC (Akaike Information Criterion) and BIC (Bayesian Information Criterion) ?
how do they perform feature selection?
provide examples of python code
Assistant
Introduction to AIC and BIC
Akaike Information Criterion (AIC) and Bayesian Information Criterion (BIC) are widely used metrics for model selection in statistical modeling and machine learning. Both criteria aim to balance model fit and model complexity to prevent overfitting, but they do so in slightly different ways.
Akaike Information Criterion (AIC):
Formula:
[ \text{AIC} = 2k - 2\ln(L) ]
where ( k ) is the number of parameters in the model, and ( L ) is the maximum likelihood of the model.
Interpretation: A lower AIC value indicates a better model. AIC penalizes models for having more parameters, encouraging simpler models that still provide a good fit to the data.
Bayesian Information Criterion (BIC):
Formula:
[ \text{BIC} = \ln(n)k - 2\ln(L) ]
where ( n ) is the number of data points, ( k ) is the number of parameters, and ( L ) is the maximum likelihood.
Interpretation: Like AIC, a lower BIC value indicates a better model. However, BIC generally imposes a harsher penalty for models with more parameters, especially as the sample size ( n ) increases.
Feature Selection Using AIC and BIC
Both AIC and BIC can be used for feature (variable) selection by evaluating and comparing different models with varying subsets of features. The process typically involves:
Model Fitting: Fit multiple models with different combinations of features.
Criterion Calculation: Compute the AIC and/or BIC for each model.
Model Comparison: Select the model with the lowest AIC or BIC value.
This approach helps in identifying a model that adequately explains the data without unnecessary complexity.
Python Examples
Below are Python examples demonstrating how to use AIC and BIC for feature selection using the statsmodels library. We'll use the Boston Housing dataset as an example.
1. Using statsmodels for AIC and BIC
python
import statsmodels.api as sm
from sklearn.datasets import load_boston
import pandas as pd
import itertools
# Load the Boston Housing dataset
boston = load_boston()
X = pd.DataFrame(boston.data, columns=boston.feature_names)
y = boston.target
# Add constant term for intercept
X = sm.add_constant(X)
# Function to calculate AIC and BIC
def calculate_aic_bic(X, y):
model = sm.OLS(y, X).fit()
return model.aic, model.bic
# Example: Compute AIC and BIC for all possible combinations of 3 features
features = boston.feature_names
best_aic = float('inf')
best_bic = float('inf')
best_aic_model = None
best_bic_model = None
for subset in itertools.combinations(features, 3):
X_subset = sm.add_constant(X[list(subset)])
aic, bic = calculate_aic_bic(X_subset, y)
if aic < best_aic:
best_aic = aic
best_aic_model = subset
if bic < best_bic:
best_bic = bic
best_bic_model = subset
print(f"Best AIC Model: {best_aic_model} with AIC = {best_aic}")
print(f"Best BIC Model: {best_bic_model} with BIC = {best_bic}")
Explanation:
Loading Data: We load the Boston Housing dataset and prepare the feature matrix X and target vector y.
Adding Intercept: An intercept term is added to the feature matrix using sm.add_constant.
Feature Selection: We iterate through all possible combinations of 3 features (for demonstration) and fit an Ordinary Least Squares (OLS) regression model for each subset.
Calculating AIC and BIC: For each model, we compute the AIC and BIC values.
Selecting Best Models: We keep track of the feature subset with the lowest AIC and BIC, respectively.
Note: Iterating through all possible combinations can be computationally intensive for large feature sets. In practice, stepwise selection methods (forward, backward, or both) are often used.
2. Forward Stepwise Selection Using AIC
Here's an example of forward stepwise selection based on AIC:
python
import statsmodels.api as sm
from sklearn.datasets import load_boston
import pandas as pd
# Load the dataset
boston = load_boston()
X = pd.DataFrame(boston.data, columns=boston.feature_names)
y = boston.target
# Initialize
selected_features = []
remaining_features = list(X.columns)
current_aic = float('inf')
best_feature = None
while remaining_features:
aic_with_candidates = []
for feature in remaining_features:
features_to_fit = selected_features + [feature]
X_subset = sm.add_constant(X[features_to_fit])
model = sm.OLS(y, X_subset).fit()
aic = model.aic
aic_with_candidates.append((aic, feature))
aic_with_candidates.sort()
best_new_aic, best_new_feature = aic_with_candidates[0]
if best_new_aic < current_aic:
selected_features.append(best_new_feature)
remaining_features.remove(best_new_feature)
current_aic = best_new_aic
print(f"Selected {best_new_feature} with AIC = {best_new_aic}")
else:
break
print(f"Final selected features: {selected_features}")
Explanation:
Initialization: Start with no selected features.
Iteration: At each step, try adding each remaining feature to the selected set and compute the AIC.
Selection: Add the feature that results in the lowest AIC if it improves the model.
Termination: Stop when no addition improves the AIC.
3. Calculating AIC and BIC with Scikit-Learn Models
While scikit-learn doesn't provide built-in methods to calculate AIC and BIC, you can compute them manually for certain models. Here's an example using Linear Regression:
python
from sklearn.linear_model import LinearRegression
from sklearn.datasets import load_boston
import numpy as np
import pandas as pd
# Load data
boston = load_boston()
X = pd.DataFrame(boston.data, columns=boston.feature_names)
y = boston.target
# Fit Linear Regression model
model = LinearRegression().fit(X, y)
# Number of observations and parameters
n = X.shape[0]
k = X.shape[1] + 1 # features + intercept
# Predict and compute residuals
y_pred = model.predict(X)
residuals = y - y_pred
rss = np.sum(residuals ** 2)
# Estimate of the variance
s2 = rss / n
# AIC and BIC calculation
aic = n * np.log(s2) + 2 * k
bic = n * np.log(s2) + np.log(n) * k
print(f"AIC: {aic}")
print(f"BIC: {bic}")
Explanation:
Fitting the Model: We use LinearRegression from scikit-learn to fit the model.
Calculating Residuals: Compute the residual sum of squares (RSS).
Estimating Variance: Estimate the variance of residuals.
AIC and BIC Computation: Use the formulas for AIC and BIC tailored for linear regression under Gaussian assumptions.
Note: This manual computation assumes that the residuals are normally distributed and that the maximum likelihood estimates for variance are used. For more accurate AIC and BIC values, especially for other types of models, it's recommended to use statsmodels or other specialized libraries.
Conclusion
AIC and BIC are powerful tools for model selection and feature selection, helping to balance model fit with complexity. By evaluating different models based on these criteria, you can select a model that generalizes well to new data without overfitting. Python libraries like statsmodels facilitate the computation of AIC and BIC, making it easier to implement these selection processes in your data analysis workflows.