What is the difference between L1 and L2 regularization in machine learning?

In the first example, we are going to implement L1 regularization in machine learning using Python.
# Step 1: Import the necessary libraries
from sklearn.linear_model import Lasso
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error

# Step 2: Generate some random data for regression
X, y = make_regression(n_features=10, n_samples=1000, noise=0.1)

# Step 3: Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

# Step 4: Fit the Lasso regression model with L1 regularization
lasso = Lasso(alpha=0.01)
lasso.fit(X_train, y_train)

# Step 5: Evaluate the model
predictions = lasso.predict(X_test)
mse = mean_squared_error(y_test, predictions)
print("Mean Squared Error:", mse)

In this example, we used the Lasso regression model which applies L1 regularization. We created a synthetic dataset, split it into training and testing sets, and then fit the Lasso model to the training data. Finally, we evaluated the model's performance on the test set by calculating the mean squared error. In the second example, let's implement L2 regularization in machine learning using Python.
# Step 1: Import the necessary libraries
from sklearn.linear_model import Ridge
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error

# Step 2: Generate some random data for regression
X, y = make_regression(n_features=10, n_samples=1000, noise=0.1)

# Step 3: Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

# Step 4: Fit the Ridge regression model with L2 regularization
ridge = Ridge(alpha=0.01)
ridge.fit(X_train, y_train)

# Step 5: Evaluate the model
predictions = ridge.predict(X_test)
mse = mean_squared_error(y_test, predictions)
print("Mean Squared Error:", mse)

In this example, we used the Ridge regression model which applies L2 regularization. We followed a similar process as in the first example by creating a synthetic dataset, splitting it into training and testing sets, fitting the Ridge model to the training data, and evaluating the model's performance on the test set. The main difference here is the type of regularization used, with L2 regularization in the Ridge model.

Comments

Popular posts from this blog

What are the different types of optimization algorithms used in deep learning?

What are the different evaluation metrics used in machine learning?

What is the difference between a module and a package in Python?