LASSO Regression
LASSO Regression
Python
It has 2 columns — “YearsExperience” and “Salary” for 30
employees in a company. So in this, we will train a Lasso
Regression model to learn the correlation between the number of
years of experience of each employee and their respective salary.
Once the model is trained, we will be able to predict the salary of
an employee on the basis of his years of experience.
Importing Libraries
Python3
# Importing libraries
import numpy as np
import pandas as pd
# Lasso Regression
class LassoRegression():
self.learning_rate = learning_rate
self.iterations = iterations
self.l1_penalty = l1_penalty
# no_of_training_examples, no_of_features
# weight initialization
self.W = np.zeros(self.n)
self.b = 0
self.X = X
self.Y = Y
for i in range(self.iterations):
self.update_weights()
return self
# Helper function to update weights in gradient descent
def update_weights(self):
Y_pred = self.predict(self.X)
# calculate gradients
dW = np.zeros(self.n)
for j in range(self.n):
if self.W[j] > 0:
self.l1_penalty) / self.m
else:
self.l1_penalty) / self.m
# update weights
return self
def main():
# Importing dataset
df = pd.read_csv("Experience-Salary.csv")
X = df.iloc[:, :-1].values
Y = df.iloc[:, 1].values
# Standardize features
scaler = StandardScaler()
X = scaler.fit_transform(X)
# Splitting dataset into train and test set
X, Y, test_size=1/3, random_state=0)
# Model training
model = LassoRegression(
model.fit(X_train, Y_train)
Y_pred = model.predict(X_test)
plt.ylabel('Salary')
plt.legend()
plt.show()
if __name__ == "__main__":
main()
Output:
Predicted values: [19.88 44.43 34.78]
Real values: [12.40492474 42.64192391 32.61398476]
Trained W: 6.84
Trained b: 26.61
Lasso Regression