224 KiB
224 KiB
In [1]:
"""
#Model training, we compute the mean value of y and X
y_train_mean = np.mean(y_train)
X_train_mean = np.mean(X_train,axis=0)
X_train = X_train - X_train_mean
y_train = y_train - y_train_mean
# The we fit our model with the training data
trained_model = some_model.fit(X_train,y_train)
#Model prediction, we need also to transform our data set used for the prediction.
X_test = X_test - X_train_mean #Use mean from training data
y_pred = trained_model(X_test)
y_pred = y_pred + y_train_mean
"""In [1]:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
np.random.seed(2021)
def MSE(y_data,y_model):
n = np.size(y_model)
return np.sum((y_data-y_model)**2)/n
def fit_beta(X, y):
return np.linalg.pinv(X.T @ X) @ X.T @ y
true_beta = [2, 0.5, 3.7]
x = np.linspace(0, 1, 11)
y = np.sum(
np.asarray([x ** p * b for p, b in enumerate(true_beta)]), axis=0
) + 0.1 * np.random.normal(size=len(x))
degree = 3
X = np.zeros((len(x), degree))
# Include the intercept in the design matrix
for p in range(degree):
X[:, p] = x ** p
beta = fit_beta(X, y)
# Intercept is included in the design matrix
skl = LinearRegression(fit_intercept=False).fit(X, y)
print(f"True beta: {true_beta}")
print(f"Fitted beta: {beta}")
print(f"Sklearn fitted beta: {skl.coef_}")
ypredictOwn = X @ beta
ypredictSKL = skl.predict(X)
print(f"MSE with intercept column")
print(MSE(y,ypredictOwn))
print(f"MSE with intercept column from SKL")
print(MSE(y,ypredictSKL))
plt.figure()
plt.scatter(x, y, label="Data")
plt.plot(x, X @ beta, label="Fit")
plt.plot(x, skl.predict(X), label="Sklearn (fit_intercept=False)")
# Do not include the intercept in the design matrix
X = np.zeros((len(x), degree - 1))
for p in range(degree - 1):
X[:, p] = x ** (p + 1)
# Intercept is not included in the design matrix
skl = LinearRegression(fit_intercept=True).fit(X, y)
# Use centered values for X and y when computing coefficients
y_offset = np.average(y, axis=0)
X_offset = np.average(X, axis=0)
beta = fit_beta(X - X_offset, y - y_offset)
intercept = np.mean(y_offset - X_offset @ beta)
print(f"Manual intercept: {intercept}")
print(f"Fitted beta (without intercept): {beta}")
print(f"Sklearn intercept: {skl.intercept_}")
print(f"Sklearn fitted beta (without intercept): {skl.coef_}")
ypredictOwn = X @ beta
ypredictSKL = skl.predict(X)
print(f"MSE with Manual intercept")
print(MSE(y,ypredictOwn+intercept))
print(f"MSE with Sklearn intercept")
print(MSE(y,ypredictSKL))
plt.plot(x, X @ beta + intercept, "--", label="Fit (manual intercept)")
plt.plot(x, skl.predict(X), "--", label="Sklearn (fit_intercept=True)")
plt.grid()
plt.legend()
plt.show()True beta: [2, 0.5, 3.7] Fitted beta: [2.08376632 0.19569961 3.97898392] Sklearn fitted beta: [2.08376632 0.19569961 3.97898392] MSE with intercept column 0.00411363461744314 MSE with intercept column from SKL 0.004113634617443147 Manual intercept: 2.083766322923899 Fitted beta (without intercept): [0.19569961 3.97898392] Sklearn intercept: 2.0837663229239043 Sklearn fitted beta (without intercept): [0.19569961 3.97898392] MSE with Manual intercept 0.00411363461744314 MSE with Sklearn intercept 0.004113634617443131
In [3]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import linear_model
def MSE(y_data,y_model):
n = np.size(y_model)
return np.sum((y_data-y_model)**2)/n
# A seed just to ensure that the random numbers are the same for every run.
# Useful for eventual debugging.
np.random.seed(3155)
n = 100
x = np.random.rand(n)
y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)
Maxpolydegree = 20
X = np.zeros((n,Maxpolydegree))
#We include explicitely the intercept column
for degree in range(Maxpolydegree):
X[:,degree] = x**degree
# We split the data in test and training data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
p = Maxpolydegree
I = np.eye(p,p)
# Decide which values of lambda to use
nlambdas = 6
MSEOwnRidgePredict = np.zeros(nlambdas)
MSERidgePredict = np.zeros(nlambdas)
lambdas = np.logspace(-4, 2, nlambdas)
for i in range(nlambdas):
lmb = lambdas[i]
OwnRidgeBeta = np.linalg.pinv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train
# Note: we include the intercept column and no scaling
RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
RegRidge.fit(X_train,y_train)
# and then make the prediction
ytildeOwnRidge = X_train @ OwnRidgeBeta
ypredictOwnRidge = X_test @ OwnRidgeBeta
ytildeRidge = RegRidge.predict(X_train)
ypredictRidge = RegRidge.predict(X_test)
MSEOwnRidgePredict[i] = MSE(y_test,ypredictOwnRidge)
MSERidgePredict[i] = MSE(y_test,ypredictRidge)
print("Beta values for own Ridge implementation")
print(OwnRidgeBeta)
print("Beta values for Scikit-Learn Ridge implementation")
print(RegRidge.coef_)
print("MSE values for own Ridge implementation")
print(MSEOwnRidgePredict[i])
print("MSE values for Scikit-Learn Ridge implementation")
print(MSERidgePredict[i])
# Now plot the results
plt.figure()
plt.plot(np.log10(lambdas), MSEOwnRidgePredict, 'r', label = 'MSE own Ridge Test')
plt.plot(np.log10(lambdas), MSERidgePredict, 'g', label = 'MSE Ridge Test')
plt.xlabel('log10(lambda)')
plt.ylabel('MSE')
plt.legend()
plt.show()Beta values for own Ridge implementation [ 1.03032441e+00 6.28336218e-02 -6.24175744e-01 5.21169159e-02 2.80847477e-01 2.12552073e-01 8.13220608e-02 -1.69634577e-02 -6.50846111e-02 -7.38962192e-02 -5.94226022e-02 -3.50227564e-02 -9.80609616e-03 1.08299273e-02 2.41882037e-02 2.93492130e-02 2.64742912e-02 1.63249532e-02 -5.01831050e-05 -2.15098090e-02] Beta values for Scikit-Learn Ridge implementation [ 1.03032441e+00 6.28336218e-02 -6.24175744e-01 5.21169159e-02 2.80847477e-01 2.12552073e-01 8.13220608e-02 -1.69634577e-02 -6.50846112e-02 -7.38962192e-02 -5.94226022e-02 -3.50227564e-02 -9.80609615e-03 1.08299273e-02 2.41882037e-02 2.93492130e-02 2.64742912e-02 1.63249532e-02 -5.01831190e-05 -2.15098090e-02] MSE values for own Ridge implementation 4.3632959111950474e-07 MSE values for Scikit-Learn Ridge implementation 4.363295916366933e-07 Beta values for own Ridge implementation [ 1.03630548 -0.01963611 -0.37900111 -0.07062318 0.12182967 0.16343471 0.13003291 0.07490892 0.02365049 -0.01449782 -0.03814292 -0.04909093 -0.05009826 -0.04389027 -0.03279636 -0.01866537 -0.00289724 0.01348565 0.02976145 0.04543942] Beta values for Scikit-Learn Ridge implementation [ 1.03630548 -0.01963611 -0.37900111 -0.07062318 0.12182967 0.16343471 0.13003291 0.07490892 0.02365049 -0.01449782 -0.03814292 -0.04909093 -0.05009826 -0.04389027 -0.03279636 -0.01866537 -0.00289724 0.01348565 0.02976145 0.04543942] MSE values for own Ridge implementation 5.194042826649355e-06 MSE values for Scikit-Learn Ridge implementation 5.194042826815211e-06 Beta values for own Ridge implementation [ 1.04220758 -0.10931453 -0.17641709 -0.06020587 0.02208512 0.05789007 0.06491736 0.05785343 0.04537385 0.03196357 0.01969145 0.00934499 0.00107405 -0.00526348 -0.00992331 -0.01318643 -0.01531845 -0.01655318 -0.01708852 -0.01708781] Beta values for Scikit-Learn Ridge implementation [ 1.04220758 -0.10931453 -0.17641709 -0.06020587 0.02208512 0.05789007 0.06491736 0.05785343 0.04537385 0.03196357 0.01969145 0.00934499 0.00107405 -0.00526348 -0.00992331 -0.01318643 -0.01531845 -0.01655318 -0.01708852 -0.01708781] MSE values for own Ridge implementation 2.0940821989652176e-05 MSE values for Scikit-Learn Ridge implementation 2.0940821989627646e-05 Beta values for own Ridge implementation [ 1.01219292 -0.06043581 -0.10391807 -0.05651951 -0.01898855 0.00312361 0.01463049 0.01975848 0.02123176 0.02068067 0.01905883 0.01691985 0.01458337 0.01223198 0.00996754 0.00784393 0.00588657 0.00410387 0.00249435 0.00105081] Beta values for Scikit-Learn Ridge implementation [ 1.01219292 -0.06043581 -0.10391807 -0.05651951 -0.01898855 0.00312361 0.01463049 0.01975848 0.02123176 0.02068067 0.01905883 0.01691985 0.01458337 0.01223198 0.00996754 0.00784393 0.00588657 0.00410387 0.00249435 0.00105081] MSE values for own Ridge implementation 0.00031535148309577417 MSE values for Scikit-Learn Ridge implementation 0.0003153514830958095 Beta values for own Ridge implementation [ 8.38916861e-01 1.31276579e-01 8.97497404e-03 -1.72271878e-02 -2.11744554e-02 -1.91492986e-02 -1.57201944e-02 -1.23002365e-02 -9.30466214e-03 -6.81048318e-03 -4.78184120e-03 -3.15130074e-03 -1.84923989e-03 -8.13661243e-04 7.46984697e-06 6.56636616e-04 1.16805821e-03 1.56912044e-03 1.88168312e-03 2.12318726e-03] Beta values for Scikit-Learn Ridge implementation [ 8.38916861e-01 1.31276579e-01 8.97497404e-03 -1.72271878e-02 -2.11744554e-02 -1.91492986e-02 -1.57201944e-02 -1.23002365e-02 -9.30466214e-03 -6.81048318e-03 -4.78184120e-03 -3.15130074e-03 -1.84923989e-03 -8.13661243e-04 7.46984697e-06 6.56636616e-04 1.16805821e-03 1.56912044e-03 1.88168312e-03 2.12318726e-03] MSE values for own Ridge implementation 0.01507238889517717 MSE values for Scikit-Learn Ridge implementation 0.01507238889517706 Beta values for own Ridge implementation [0.37396662 0.14174745 0.0764924 0.04892055 0.03447512 0.02586427 0.02024962 0.01633913 0.01347916 0.0113104 0.0096208 0.00827728 0.00719176 0.00630331 0.00556826 0.0049544 0.00443743 0.0039987 0.0036237 0.003301 ] Beta values for Scikit-Learn Ridge implementation [0.37396662 0.14174745 0.0764924 0.04892055 0.03447512 0.02586427 0.02024962 0.01633913 0.01347916 0.0113104 0.0096208 0.00827728 0.00719176 0.00630331 0.00556826 0.0049544 0.00443743 0.0039987 0.0036237 0.003301 ] MSE values for own Ridge implementation 0.2640931530791004 MSE values for Scikit-Learn Ridge implementation 0.26409315307910025
In [4]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import linear_model
from sklearn.preprocessing import StandardScaler
def MSE(y_data,y_model):
n = np.size(y_model)
return np.sum((y_data-y_model)**2)/n
# A seed just to ensure that the random numbers are the same for every run.
# Useful for eventual debugging.
np.random.seed(315)
n = 100
x = np.random.rand(n)
y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)
Maxpolydegree = 20
X = np.zeros((n,Maxpolydegree-1))
for degree in range(1,Maxpolydegree): #No intercept column
X[:,degree-1] = x**(degree)
# We split the data in test and training data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
#For our own implementation, we will need to deal with the intercept by centering the design matrix and the target variable
X_train_mean = np.mean(X_train,axis=0)
#Center by removing mean from each feature
X_train_scaled = X_train - X_train_mean
X_test_scaled = X_test - X_train_mean
#The model intercept (called y_scaler) is given by the mean of the target variable (IF X is centered)
#Remove the intercept from the training data.
y_scaler = np.mean(y_train)
y_train_scaled = y_train - y_scaler
p = Maxpolydegree-1
I = np.eye(p,p)
# Decide which values of lambda to use
nlambdas = 6
MSEOwnRidgePredict = np.zeros(nlambdas)
MSERidgePredict = np.zeros(nlambdas)
lambdas = np.logspace(-4, 2, nlambdas)
for i in range(nlambdas):
lmb = lambdas[i]
OwnRidgeBeta = np.linalg.pinv(X_train_scaled.T @ X_train_scaled+lmb*I) @ X_train_scaled.T @ (y_train_scaled)
intercept_ = y_scaler - X_train_mean@OwnRidgeBeta #The intercept can be shifted so the model can predict on uncentered data
#Add intercept to prediction
ypredictOwnRidge = X_test_scaled @ OwnRidgeBeta + y_scaler
RegRidge = linear_model.Ridge(lmb)
RegRidge.fit(X_train,y_train)
ypredictRidge = RegRidge.predict(X_test)
MSEOwnRidgePredict[i] = MSE(y_test,ypredictOwnRidge)
MSERidgePredict[i] = MSE(y_test,ypredictRidge)
print("Beta values for own Ridge implementation")
print(OwnRidgeBeta) #Intercept is given by mean of target variable
print("Beta values for Scikit-Learn Ridge implementation")
print(RegRidge.coef_)
print('Intercept from own implementation:')
print(intercept_)
print('Intercept from Scikit-Learn Ridge implementation')
print(RegRidge.intercept_)
print("MSE values for own Ridge implementation")
print(MSEOwnRidgePredict[i])
print("MSE values for Scikit-Learn Ridge implementation")
print(MSERidgePredict[i])
# Now plot the results
plt.figure()
plt.plot(np.log10(lambdas), MSEOwnRidgePredict, 'b--', label = 'MSE own Ridge Test')
plt.plot(np.log10(lambdas), MSERidgePredict, 'g--', label = 'MSE SL Ridge Test')
plt.xlabel('log10(lambda)')
plt.ylabel('MSE')
plt.legend()
plt.show()Beta values for own Ridge implementation [ 3.43579948e-02 -5.43330971e-01 -3.10141413e-03 2.47116868e-01 2.18613217e-01 1.02054837e-01 -4.25617658e-04 -5.90475506e-02 -7.68534263e-02 -6.68929213e-02 -4.24906604e-02 -1.40927184e-02 1.11482289e-02 2.88529063e-02 3.67047975e-02 3.38135733e-02 2.02198703e-02 -3.46383926e-03 -3.63025821e-02] Beta values for Scikit-Learn Ridge implementation [ 3.43579948e-02 -5.43330971e-01 -3.10141413e-03 2.47116868e-01 2.18613217e-01 1.02054837e-01 -4.25617655e-04 -5.90475506e-02 -7.68534263e-02 -6.68929213e-02 -4.24906604e-02 -1.40927184e-02 1.11482289e-02 2.88529063e-02 3.67047975e-02 3.38135733e-02 2.02198702e-02 -3.46383925e-03 -3.63025821e-02] Intercept from own implementation: 1.0330308045187757 Intercept from Scikit-Learn Ridge implementation 1.0330308045183194 MSE values for own Ridge implementation 3.139255958997547e-06 MSE values for Scikit-Learn Ridge implementation 3.1392559585020426e-06 Beta values for own Ridge implementation [-0.05807125 -0.29822833 -0.08551306 0.08156108 0.13679863 0.12333649 0.08251519 0.03815288 0.00111756 -0.02498832 -0.04010697 -0.04566964 -0.04355837 -0.03562355 -0.02348765 -0.00848904 0.00831018 0.0260906 0.04423486] Beta values for Scikit-Learn Ridge implementation [-0.05807125 -0.29822833 -0.08551306 0.08156108 0.13679863 0.12333649 0.08251519 0.03815288 0.00111756 -0.02498832 -0.04010697 -0.04566964 -0.04355837 -0.03562355 -0.02348765 -0.00848904 0.00831018 0.0260906 0.04423486] Intercept from own implementation: 1.0411487294305088 Intercept from Scikit-Learn Ridge implementation 1.0411487294305226 MSE values for own Ridge implementation 1.9601304850035702e-05 MSE values for Scikit-Learn Ridge implementation 1.9601304850073734e-05 Beta values for own Ridge implementation [-0.1416398 -0.14021063 -0.05383795 0.01367553 0.04784395 0.05796251 0.05447415 0.044613 0.03267527 0.02098261 0.01066519 0.00217499 -0.00440346 -0.00917248 -0.01231917 -0.01405935 -0.0146081 -0.01416528 -0.01290947] Beta values for Scikit-Learn Ridge implementation [-0.1416398 -0.14021063 -0.05383795 0.01367553 0.04784395 0.05796251 0.05447415 0.044613 0.03267527 0.02098261 0.01066519 0.00217499 -0.00440346 -0.00917248 -0.01231917 -0.01405935 -0.0146081 -0.01416528 -0.01290947] Intercept from own implementation: 1.049556996627824 Intercept from Scikit-Learn Ridge implementation 1.0495569966278269 MSE values for own Ridge implementation 5.4959161509357395e-05 MSE values for Scikit-Learn Ridge implementation 5.4959161509366685e-05 Beta values for own Ridge implementation [-0.13535942 -0.08593216 -0.03568439 -0.0036367 0.01397146 0.02229529 0.02503753 0.0245528 0.02228115 0.01908936 0.01549377 0.01179792 0.00817631 0.00472512 0.00149311 -0.00149956 -0.00424967 -0.00676387 -0.00905423] Beta values for Scikit-Learn Ridge implementation [-0.13535942 -0.08593216 -0.03568439 -0.0036367 0.01397146 0.02229529 0.02503753 0.0245528 0.02228115 0.01908936 0.01549377 0.01179792 0.00817631 0.00472512 0.00149311 -0.00149956 -0.00424967 -0.00676387 -0.00905423] Intercept from own implementation: 1.039967668952797 Intercept from Scikit-Learn Ridge implementation 1.0399676689527975 MSE values for own Ridge implementation 7.571105947979344e-05 MSE values for Scikit-Learn Ridge implementation 7.571105947979412e-05 Beta values for own Ridge implementation [-0.05100875 -0.04063602 -0.02723445 -0.01713366 -0.0100706 -0.00517114 -0.00174276 0.00068734 0.00243186 0.00369758 0.00462287 0.0053018 0.00579953 0.006162 0.00642221 0.00660427 0.00672607 0.0068011 0.00683964] Beta values for Scikit-Learn Ridge implementation [-0.05100875 -0.04063602 -0.02723445 -0.01713366 -0.0100706 -0.00517114 -0.00174276 0.00068734 0.00243186 0.00369758 0.00462287 0.0053018 0.00579953 0.006162 0.00642221 0.00660427 0.00672607 0.0068011 0.00683964] Intercept from own implementation: 0.999955585168597 Intercept from Scikit-Learn Ridge implementation 0.999955585168597 MSE values for own Ridge implementation 0.0007698473260556343 MSE values for Scikit-Learn Ridge implementation 0.0007698473260556325 Beta values for own Ridge implementation [-0.00834567 -0.00803064 -0.00673407 -0.00554552 -0.00458878 -0.0038335 -0.00323332 -0.00274989 -0.0023548 -0.00202756 -0.00175331 -0.00152117 -0.001323 -0.0011526 -0.00100519 -0.00087697 -0.00076495 -0.00066668 -0.00058016] Beta values for Scikit-Learn Ridge implementation [-0.00834567 -0.00803064 -0.00673407 -0.00554552 -0.00458878 -0.0038335 -0.00323332 -0.00274989 -0.0023548 -0.00202756 -0.00175331 -0.00152117 -0.001323 -0.0011526 -0.00100519 -0.00087697 -0.00076495 -0.00066668 -0.00058016] Intercept from own implementation: 0.9637117593816477 Intercept from Scikit-Learn Ridge implementation 0.9637117593816477 MSE values for own Ridge implementation 0.0023813163025848865 MSE values for Scikit-Learn Ridge implementation 0.002381316302584885
In [5]:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import linear_model
def R2(y_data, y_model):
return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
def MSE(y_data,y_model):
n = np.size(y_model)
return np.sum((y_data-y_model)**2)/n
# Make data set.
n = 10000
x = np.random.rand(n)
y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
Maxpolydegree = 5
X = np.zeros((len(x),Maxpolydegree))
X[:,0] = 1.0
for polydegree in range(1,Maxpolydegree):
X[:,polydegree] = x**(polydegree)
# We split the data in test and training data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# matrix inversion to find beta
OLSbeta = np.linalg.pinv(X_train.T @ X_train) @ X_train.T @ y_train
print(OLSbeta)
ypredictOLS = X_test @ OLSbeta
print("Test MSE OLS")
print(MSE(y_test,ypredictOLS))
# Repeat now for Lasso and Ridge regression and various values of the regularization parameter using Scikit-Learn
# Decide which values of lambda to use
nlambdas = 4
MSERidgePredict = np.zeros(nlambdas)
MSELassoPredict = np.zeros(nlambdas)
lambdas = np.logspace(-3, 1, nlambdas)
for i in range(nlambdas):
lmb = lambdas[i]
# Make the fit using Ridge and Lasso
RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
RegRidge.fit(X_train,y_train)
RegLasso = linear_model.Lasso(lmb,fit_intercept=False)
RegLasso.fit(X_train,y_train)
# and then make the prediction
ypredictRidge = RegRidge.predict(X_test)
ypredictLasso = RegLasso.predict(X_test)
# Compute the MSE and print it
MSERidgePredict[i] = MSE(y_test,ypredictRidge)
MSELassoPredict[i] = MSE(y_test,ypredictLasso)
print(lmb,RegRidge.coef_)
print(lmb,RegLasso.coef_)
# Now plot the results
plt.figure()
plt.plot(np.log10(lambdas), MSERidgePredict, 'b', label = 'MSE Ridge Test')
plt.plot(np.log10(lambdas), MSELassoPredict, 'r', label = 'MSE Lasso Test')
plt.xlabel('log10(lambda)')
plt.ylabel('MSE')
plt.legend()
plt.show()Warning:
Output truncated. This notebook contains too many cells to display efficiently.