<jupyter_start><jupyter_text>Lasso Regression Part 2 Lasso Regression (Least Absolute Shrinkage and Selection Operator) is a method that performs both variable selection and regularization in order to enhance the prediction accuracy and interpretability of the statistical model it produces.<jupyter_code>import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

import warnings
warnings.filterwarnings("ignore")

# yfinance is used to fetch data 
import yfinance as yf
yf.pdr_override()
# input
symbol = 'AMD'
start = '2014-01-01'
end = '2018-08-27'

# Read data 
dataset = yf.download(symbol,start,end)

# View Columns
dataset.head()
X = dataset[['Open','High', 'Low']]
Y = dataset['Adj Close']
from sklearn.linear_model import Lasso
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

X_train,X_test,y_train,y_test=train_test_split(X,Y, test_size=0.3, random_state=0)
model = Lasso()
model.fit(X_train,y_train)
train_score=model.score(X_train,y_train)
test_score=model.score(X_test,y_test)
coeff_used = np.sum(model.coef_!=0)
print("Training score:", train_score)
print("Test score: ", test_score)
print("Number of features used: ", coeff_used)
print("Accuracy Score: ", model.score(X_test, y_test))
r_squared = model.score(X_test, y_test)
print("The model can predict {0:.1%} of the variance in the test set.".format(r_squared))
zero_coef = model.coef_ == 0
n_ignored = sum(zero_coef)
print("The model has ignored {} out of {} features.".format(n_ignored, len(model.coef_)))
model = Lasso(alpha=0.1, random_state=0)

# Fits the model and calculates performance stats
model.fit(X_train, y_train)
r_squared = model.score(X_test, y_test)
n_ignored_features = sum(model.coef_ == 0)

# Print peformance stats 
print("The model can predict {0:.1%} of the variance in the test set.".format(r_squared))
print("{} out of {} features were ignored.".format(n_ignored_features, len( model.coef_)))
model.score(X_test, y_test)
from sklearn.metrics import r2_score

y_pred_lasso = model.fit(X_train, y_train).predict(X_test)
r2_score_lasso = r2_score(y_test, y_pred_lasso)

print("r^2 on test data : %f" % r2_score_lasso)
plt.plot(model.coef_, color='gold', linewidth=2,
         label='Lasso coefficients')
plt.legend(loc='best')
plt.title("Lasso R^2: %f" % (r2_score_lasso))
plt.show()<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup