Ridge and Lasso
Ridge and Lasso
Ridge and Lasso Regression: Ridge and LASSO Regression: Load the Housing Price dataset and fit a LASSO regression model to identify the
optimal 𝜆 λ (learning rate). Determine which variables are eliminated by LASSO. Also, fit a Ridge regression model to the dataset and compare
the accuracy of both models.
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LassoCV, RidgeCV
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import StandardScaler
df = pd.read_csv("Housing.csv")
X = df.drop("price", axis=1)
y = df["price"]
X = pd.get_dummies(X, drop_first=True)
plt.figure(figsize=(12, 10))
sns.heatmap(X.corr(), annot=True, cmap="coolwarm", fmt=".2f", linewidths=0.5)
plt.title("Feature Correlation Heatmap")
plt.show()
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
lasso_pred = lasso.predict(X_test)
ridge_pred = ridge.predict(X_test)
https://colab.research.google.com/drive/1XGd51BZRDY3cNmpDxqiRYlooVPEp0AHd#printMode=true 1/2
12/16/24, 9:33 PM SML-LAB4 - Colab
https://colab.research.google.com/drive/1XGd51BZRDY3cNmpDxqiRYlooVPEp0AHd#printMode=true 2/2