Certainly! Below is a step-by-step Python example that implements Principal Components Regression (PCR) followed by Ridge Regression on the principal components. It also includes:
- Output of PCR coefficients,
- A plot of Ridge coefficients vs. lambda (regularization parameter),
- Selection of the optimal lambda using cross-validation.
Assumptions:
- Your data is in a pandas DataFrame
df.
- The first column is the target variable.
- The next 10 columns are features.
Required libraries:
pip install numpy pandas scikit-learn matplotlib
Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.linear_model import RidgeCV, Ridge
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
# Example: Load your data into df
# df = pd.read_csv('your_data.csv')
# Separate target and features
y = df.iloc[:, 0].values
X = df.iloc[:, 1:].values
# Standardize features (important for PCA and Ridge)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Step 1: Apply PCA
pca = PCA(n_components=X.shape[1])
X_pca = pca.fit_transform(X_scaled)
# Step 2: Principal Components Regression (PCR)
# Regress y on the principal components using OLS (no regularization)
from sklearn.linear_model import LinearRegression
lr = LinearRegression()
lr.fit(X_pca, y)
pcr_coefs = lr.coef_
print("PCR coefficients (on principal components):")
print(pcr_coefs)
# Step 3: Ridge Regression on principal components
# Define a range of lambdas (alphas in sklearn)
alphas = np.logspace(-4, 4, 100)
# Use RidgeCV to select the best alpha with built-in cross-validation
ridge_cv = RidgeCV(alphas=alphas, store_cv_values=True)
ridge_cv.fit(X_pca, y)
print(f"Optimal lambda (alpha) from cross-validation: {ridge_cv.alpha_}")
# Step 4: Plot coefficients vs lambda
coefs = []
for a in alphas:
ridge = Ridge(alpha=a)
ridge.fit(X_pca, y)
coefs.append(ridge.coef_)
coefs = np.array(coefs)
plt.figure(figsize=(10, 6))
for i in range(coefs.shape[1]):
plt.plot(alphas, coefs[:, i], label=f'PC{i+1}')
plt.xscale('log')
plt.xlabel('Lambda (alpha)')
plt.ylabel('Coefficient value')
plt.title('Ridge coefficients vs Lambda')
plt.axvline(ridge_cv.alpha_, color='red', linestyle='--', label='Optimal lambda')
plt.legend()
plt.show()
Explanation:
- StandardScaler: PCA and Ridge are sensitive to feature scaling.
- PCA: Transforms features into orthogonal principal components.
- PCR: Linear regression on all principal components.
- RidgeCV: Performs Ridge regression with cross-validation to find the best lambda.
- Plot: Shows how coefficients shrink as lambda increases, with the optimal lambda marked.
If you want me to help you adapt this to your specific dataset or add more details (e.g., reconstructing coefficients in original feature space), just ask!