Elastic Net Regression with Python & Sklearn

Python

Elastic Net is a linear regression algorithm that uses a combination of L1 and L2 regularisation so can be thought of as a blend of Lasso and Ridge regression algorithms.

In the code snippet below we initialise and fit a model that combines an equal blend of L1 and L2 regularisation before evaluating the model against test data.

 1|  from sklearn.linear_model import ElasticNet
 2|  from sklearn.metrics import mean_squared_error, mean_absolute_error, max_error, explained_variance_score, mean_absolute_percentage_error
 3|  
 4|  # initialise & fit Elastic Net regression model with alpha set to 0.1
 5|  # and 50/50 blend between l1 and l2 regularisation
 6|  model = ElasticNet(alpha=0.1, l1_ratio=0.5)
 7|  model.fit(X_train, y_train)
 8|  
 9|  # make prediction for test data & evaluate performance
10|  y_pred = model.predict(X_test)
11|  print('RMSE:',mean_squared_error(y_test, y_pred, squared = False))
12|  print('MAE:',mean_absolute_error(y_test, y_pred))
13|  print('MAPE:',mean_absolute_percentage_error(y_test, y_pred))
14|  print('Max Error:',max_error(y_test, y_pred))
15|  print('Explained Variance Score:',explained_variance_score(y_test, y_pred))
Did you find this snippet useful?

Sign up for free to to add this to your code library