jupyter nbconvert --to terminal mlps/04 - Regressione Lineare.ipynb
MDN-118:08

04 Regressione Lineare

04 - Regressione Lineare.ipynb · 1,1 MB · scarica
In [1]:
from sklearn.datasets import fetch_california_housing
data = fetch_california_housing(as_frame=True)
import pandas as pd
df = pd.DataFrame(data.frame)
df.head()
.dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; }
MedInc HouseAge AveRooms AveBedrms Population AveOccup Latitude Longitude MedHouseVal
0 8.3252 41.0 6.984127 1.023810 322.0 2.555556 37.88 -122.23 4.526
1 8.3014 21.0 6.238137 0.971880 2401.0 2.109842 37.86 -122.22 3.585
2 7.2574 52.0 8.288136 1.073446 496.0 2.802260 37.85 -122.24 3.521
3 5.6431 52.0 5.817352 1.073059 558.0 2.547945 37.85 -122.25 3.413
4 3.8462 52.0 6.281853 1.081081 565.0 2.181467 37.85 -122.25 3.422
.colab-df-container { display:flex; flex-wrap:wrap; gap: 12px; } .colab-df-convert { background-color: #E8F0FE; border: none; border-radius: 50%; cursor: pointer; display: none; fill: #1967D2; height: 32px; padding: 0 0 0 0; width: 32px; } .colab-df-convert:hover { background-color: #E2EBFA; box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15); fill: #174EA6; } [theme=dark] .colab-df-convert { background-color: #3B4455; fill: #D2E3FC; } [theme=dark] .colab-df-convert:hover { background-color: #434B5C; box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15); filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3)); fill: #FFFFFF; } const buttonEl = document.querySelector('#df-9ee96ab8-2de4-430c-963b-19526a846997 button.colab-df-convert'); buttonEl.style.display = google.colab.kernel.accessAllowed ? 'block' : 'none'; async function convertToInteractive(key) { const element = document.querySelector('#df-9ee96ab8-2de4-430c-963b-19526a846997'); const dataTable = await google.colab.kernel.invokeFunction('convertToInteractive', [key], {}); if (!dataTable) return; const docLinkHtml = 'Like what you see? Visit the ' + 'data table notebook' + ' to learn more about interactive tables.'; element.innerHTML = ''; dataTable['output_type'] = 'display_data'; await google.colab.output.renderOutput(dataTable, element); const docLink = document.createElement('div'); docLink.innerHTML = docLinkHtml; element.appendChild(docLink); }
In [2]:
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 20640 entries, 0 to 20639
Data columns (total 9 columns):
 #   Column       Non-Null Count  Dtype  
---  ------       --------------  -----  
 0   MedInc       20640 non-null  float64
 1   HouseAge     20640 non-null  float64
 2   AveRooms     20640 non-null  float64
 3   AveBedrms    20640 non-null  float64
 4   Population   20640 non-null  float64
 5   AveOccup     20640 non-null  float64
 6   Latitude     20640 non-null  float64
 7   Longitude    20640 non-null  float64
 8   MedHouseVal  20640 non-null  float64
dtypes: float64(9)
memory usage: 1.4 MB
In [3]:
# verifichiamo la presenza di valori missing
df.isnull().sum()
MedInc         0
HouseAge       0
AveRooms       0
AveBedrms      0
Population     0
AveOccup       0
Latitude       0
Longitude      0
MedHouseVal    0
dtype: int64
In [4]:
X = df.drop(['MedHouseVal'], axis=1)
y = df['MedHouseVal']
In [5]:
# visualizzo la variabile target
import matplotlib.pyplot as plt
plt.figure(figsize=(5, 4))
plt.hist(y)
plt.title('Valore medio abitazioni')
plt.xlabel('Prezzo')
plt.ylabel('Conteggio')
plt.show()
In [6]:
import seaborn as sns
sns.pairplot(X)
<seaborn.axisgrid.PairGrid at 0x7f4f32247250>
In [7]:
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2)
print(X_train.shape)
print(y_train.shape)
print(X_test.shape)
print(y_test.shape)
(16512, 8)
(16512,)
(4128, 8)
(4128,)

LINEAR REGRESSION

In [8]:
from sklearn.linear_model import LinearRegression
lr = LinearRegression()
lr.fit(X_train, y_train)
LinearRegression()
In [9]:
predict = lr.predict(X_test)
In [10]:
from sklearn.metrics import mean_squared_error

# calcolo il MSE per il dataset di test
mse_tst = mean_squared_error(y_test, predict)
print(f"Il Mean Squared error del test set è : {mse_tst:.3f}")
Il Mean Squared error del test set è : 0.522
In [11]:
from sklearn.metrics import r2_score

# calcolo punteggio R2 per il dataset di test
r2_tst = r2_score(y_test, predict)
print(f"Il punteggio R2 del test set è : {r2_tst:.3f}")
Il punteggio R2 del test set è : 0.601
In [12]:
# confrontiamo l'output reale con quello previsto
plt.figure(figsize=(6, 4))
plt.scatter(y_test, predict)
plt.xlabel("Prezzi Reali")
plt.ylabel("Prezzi Previsti")
plt.title("Prezzi reali vs Prezzi previsti")
plt.show()
In [13]:
corrMatrix = X.corr()
print (corrMatrix)
              MedInc  HouseAge  AveRooms  AveBedrms  Population  AveOccup  \
MedInc      1.000000 -0.119034  0.326895  -0.062040    0.004834  0.018766   
HouseAge   -0.119034  1.000000 -0.153277  -0.077747   -0.296244  0.013191   
AveRooms    0.326895 -0.153277  1.000000   0.847621   -0.072213 -0.004852   
AveBedrms  -0.062040 -0.077747  0.847621   1.000000   -0.066197 -0.006181   
Population  0.004834 -0.296244 -0.072213  -0.066197    1.000000  0.069863   
AveOccup    0.018766  0.013191 -0.004852  -0.006181    0.069863  1.000000   
Latitude   -0.079809  0.011173  0.106389   0.069721   -0.108785  0.002366   
Longitude  -0.015176 -0.108197 -0.027540   0.013344    0.099773  0.002476   

            Latitude  Longitude  
MedInc     -0.079809  -0.015176  
HouseAge    0.011173  -0.108197  
AveRooms    0.106389  -0.027540  
AveBedrms   0.069721   0.013344  
Population -0.108785   0.099773  
AveOccup    0.002366   0.002476  
Latitude    1.000000  -0.924664  
Longitude  -0.924664   1.000000  
In [14]:
sns.heatmap(corrMatrix, annot=True)
plt.show()
In [15]:
# confrontiamo latitudine e longitudine
plt.figure(figsize=(6, 4))
plt.scatter(X['Latitude'], X['Longitude'], c=y, cmap='YlGn')
plt.show()

Se ci focalizziamo su "AveRooms", "AveBedrms", "AveOccup", "Population", possiamo notare dal grafico delle loro distribuzioni che ci sono pochi valori molto alti, che potrebbero essere considerati come outliers. Andiamo a verificarlo:

In [16]:
check = ["AveRooms", "AveBedrms", "AveOccup", "Population"]
df[check].describe()
.dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; }
AveRooms AveBedrms AveOccup Population
count 20640.000000 20640.000000 20640.000000 20640.000000
mean 5.429000 1.096675 3.070655 1425.476744
std 2.474173 0.473911 10.386050 1132.462122
min 0.846154 0.333333 0.692308 3.000000
25% 4.440716 1.006079 2.429741 787.000000
50% 5.229129 1.048780 2.818116 1166.000000
75% 6.052381 1.099526 3.282261 1725.000000
max 141.909091 34.066667 1243.333333 35682.000000
.colab-df-container { display:flex; flex-wrap:wrap; gap: 12px; } .colab-df-convert { background-color: #E8F0FE; border: none; border-radius: 50%; cursor: pointer; display: none; fill: #1967D2; height: 32px; padding: 0 0 0 0; width: 32px; } .colab-df-convert:hover { background-color: #E2EBFA; box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15); fill: #174EA6; } [theme=dark] .colab-df-convert { background-color: #3B4455; fill: #D2E3FC; } [theme=dark] .colab-df-convert:hover { background-color: #434B5C; box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15); filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3)); fill: #FFFFFF; } const buttonEl = document.querySelector('#df-c52a9bb1-cc43-4ddb-964e-f75e4c00e50a button.colab-df-convert'); buttonEl.style.display = google.colab.kernel.accessAllowed ? 'block' : 'none'; async function convertToInteractive(key) { const element = document.querySelector('#df-c52a9bb1-cc43-4ddb-964e-f75e4c00e50a'); const dataTable = await google.colab.kernel.invokeFunction('convertToInteractive', [key], {}); if (!dataTable) return; const docLinkHtml = 'Like what you see? Visit the ' + 'data table notebook' + ' to learn more about interactive tables.'; element.innerHTML = ''; dataTable['output_type'] = 'display_data'; await google.colab.output.renderOutput(dataTable, element); const docLink = document.createElement('div'); docLink.innerHTML = docLinkHtml; element.appendChild(docLink); }
In [17]:
from scipy import stats
import numpy as np
z_scores = stats.zscore(df)

abs_z_scores = np.abs(z_scores)
filtered_entries = (abs_z_scores < 3).all(axis=1)
df = df[filtered_entries]
In [18]:
df[check].describe()
.dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; }
AveRooms AveBedrms AveOccup Population
count 19794.000000 19794.000000 19794.000000 19794.000000
mean 5.243471 1.068965 2.931222 1344.441598
std 1.221588 0.135362 0.884634 811.791606
min 0.846154 0.333333 0.750000 3.000000
25% 4.417435 1.005442 2.426490 792.000000
50% 5.185518 1.048193 2.816485 1162.000000
75% 5.970846 1.098284 3.284288 1696.000000
max 12.447368 2.514610 33.952941 4819.000000
.colab-df-container { display:flex; flex-wrap:wrap; gap: 12px; } .colab-df-convert { background-color: #E8F0FE; border: none; border-radius: 50%; cursor: pointer; display: none; fill: #1967D2; height: 32px; padding: 0 0 0 0; width: 32px; } .colab-df-convert:hover { background-color: #E2EBFA; box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15); fill: #174EA6; } [theme=dark] .colab-df-convert { background-color: #3B4455; fill: #D2E3FC; } [theme=dark] .colab-df-convert:hover { background-color: #434B5C; box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15); filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3)); fill: #FFFFFF; } const buttonEl = document.querySelector('#df-0331396a-fe56-483e-8032-c80caa990464 button.colab-df-convert'); buttonEl.style.display = google.colab.kernel.accessAllowed ? 'block' : 'none'; async function convertToInteractive(key) { const element = document.querySelector('#df-0331396a-fe56-483e-8032-c80caa990464'); const dataTable = await google.colab.kernel.invokeFunction('convertToInteractive', [key], {}); if (!dataTable) return; const docLinkHtml = 'Like what you see? Visit the ' + 'data table notebook' + ' to learn more about interactive tables.'; element.innerHTML = ''; dataTable['output_type'] = 'display_data'; await google.colab.output.renderOutput(dataTable, element); const docLink = document.createElement('div'); docLink.innerHTML = docLinkHtml; element.appendChild(docLink); }
In [19]:
X = df.drop(['MedHouseVal'], axis=1)
y = df['MedHouseVal']
In [20]:
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2)
lr.fit(X_train, y_train)
predict = lr.predict(X_test)
mse_tst = mean_squared_error(y_test, predict)
print(f"Il Mean Squared error del test set è : {mse_tst:.3f}")
r2_tst = r2_score(y_test, predict)
print(f"Il punteggio R2 del test set è : {r2_tst:.3f}")
Il Mean Squared error del test set è : 0.457
Il punteggio R2 del test set è : 0.635

LASSO REGRESSION

In [22]:
from sklearn.linear_model import Lasso
lasso_r = Lasso(alpha = 1, fit_intercept= True, normalize= False, max_iter = 20000)
lasso_r.fit(X_train, y_train)
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:155: FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2. Please leave the normalize parameter to its default value to silence this warning. The default behavior of this estimator is to not do any normalization. If normalization is needed please use sklearn.preprocessing.StandardScaler instead.
  FutureWarning,
Lasso(alpha=1, max_iter=20000, normalize=False)
In [23]:
predict = lasso_r.predict(X_test)
In [24]:
# calcolo il MSE per il dataset di test
mse_tst = mean_squared_error(y_test, predict)
print(f"Il Mean Squared error del test set è : {mse_tst:.3f}")
Il Mean Squared error del test set è : 1.089
In [25]:
# calcolo punteggio R2 per il dataset di test
r2_tst = r2_score(y_test, predict)
print(f"Il punteggio R2 del test set è : {r2_tst:.3f}")
Il punteggio R2 del test set è : 0.132
In [33]:
from sklearn.model_selection import GridSearchCV

lasso_r_parameter = {'alpha': [0.2,0.4,0.6,0.8,1], 'normalize': [True, False], 'fit_intercept': [True, False]}
lasso_r_grid_search = GridSearchCV(Lasso(max_iter = 400000), lasso_r_parameter, cv = 2)
lasso_r_grid_search.fit(X_train, y_train)
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:145: FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2.
If you wish to scale the data, use Pipeline with a StandardScaler in a preprocessing stage. To reproduce the previous behavior:

from sklearn.pipeline import make_pipeline

model = make_pipeline(StandardScaler(with_mean=False), Lasso())

If you wish to pass a sample_weight parameter, you need to pass it as a fit parameter to each step of the pipeline as follows:

kwargs = {s[0] + '__sample_weight': sample_weight for s in model.steps}
model.fit(X, y, **kwargs)

Set parameter alpha to: original_alpha * np.sqrt(n_samples). 
  FutureWarning,
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:145: FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2.
If you wish to scale the data, use Pipeline with a StandardScaler in a preprocessing stage. To reproduce the previous behavior:

from sklearn.pipeline import make_pipeline

model = make_pipeline(StandardScaler(with_mean=False), Lasso())

If you wish to pass a sample_weight parameter, you need to pass it as a fit parameter to each step of the pipeline as follows:

kwargs = {s[0] + '__sample_weight': sample_weight for s in model.steps}
model.fit(X, y, **kwargs)

Set parameter alpha to: original_alpha * np.sqrt(n_samples). 
  FutureWarning,
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:155: FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2. Please leave the normalize parameter to its default value to silence this warning. The default behavior of this estimator is to not do any normalization. If normalization is needed please use sklearn.preprocessing.StandardScaler instead.
  FutureWarning,
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:155: FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2. Please leave the normalize parameter to its default value to silence this warning. The default behavior of this estimator is to not do any normalization. If normalization is needed please use sklearn.preprocessing.StandardScaler instead.
  FutureWarning,
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:145: FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2.
If you wish to scale the data, use Pipeline with a StandardScaler in a preprocessing stage. To reproduce the previous behavior:

from sklearn.pipeline import make_pipeline

model = make_pipeline(StandardScaler(with_mean=False), Lasso())

If you wish to pass a sample_weight parameter, you need to pass it as a fit parameter to each step of the pipeline as follows:

kwargs = {s[0] + '__sample_weight': sample_weight for s in model.steps}
model.fit(X, y, **kwargs)

Set parameter alpha to: original_alpha * np.sqrt(n_samples). 
  FutureWarning,
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:145: FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2.
If you wish to scale the data, use Pipeline with a StandardScaler in a preprocessing stage. To reproduce the previous behavior:

from sklearn.pipeline import make_pipeline

model = make_pipeline(StandardScaler(with_mean=False), Lasso())

If you wish to pass a sample_weight parameter, you need to pass it as a fit parameter to each step of the pipeline as follows:

kwargs = {s[0] + '__sample_weight': sample_weight for s in model.steps}
model.fit(X, y, **kwargs)

Set parameter alpha to: original_alpha * np.sqrt(n_samples). 
  FutureWarning,
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:155: FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2. Please leave the normalize parameter to its default value to silence this warning. The default behavior of this estimator is to not do any normalization. If normalization is needed please use sklearn.preprocessing.StandardScaler instead.
  FutureWarning,
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:155: FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2. Please leave the normalize parameter to its default value to silence this warning. The default behavior of this estimator is to not do any normalization. If normalization is needed please use sklearn.preprocessing.StandardScaler instead.
  FutureWarning,
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:145: FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2.
If you wish to scale the data, use Pipeline with a StandardScaler in a preprocessing stage. To reproduce the previous behavior:

from sklearn.pipeline import make_pipeline

model = make_pipeline(StandardScaler(with_mean=False), Lasso())

If you wish to pass a sample_weight parameter, you need to pass it as a fit parameter to each step of the pipeline as follows:

kwargs = {s[0] + '__sample_weight': sample_weight for s in model.steps}
model.fit(X, y, **kwargs)

Set parameter alpha to: original_alpha * np.sqrt(n_samples). 
  FutureWarning,
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:145: FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2.
If you wish to scale the data, use Pipeline with a StandardScaler in a preprocessing stage. To reproduce the previous behavior:

from sklearn.pipeline import make_pipeline

model = make_pipeline(StandardScaler(with_mean=False), Lasso())

If you wish to pass a sample_weight parameter, you need to pass it as a fit parameter to each step of the pipeline as follows:

kwargs = {s[0] + '__sample_weight': sample_weight for s in model.steps}
model.fit(X, y, **kwargs)

Set parameter alpha to: original_alpha * np.sqrt(n_samples). 
  FutureWarning,
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:155: FutureWarning: 'normalize' was deprecated in version
… [output troncato]
GridSearchCV(cv=2, estimator=Lasso(max_iter=400000),
             param_grid={'alpha': [0.2, 0.4, 0.6, 0.8, 1],
                         'fit_intercept': [True, False],
                         'normalize': [True, False]})
In [34]:
print('Il miglior score: ',lasso_r_grid_search.best_score_)
print('I migliori parametri: ',lasso_r_grid_search.best_params_)
Il miglior score:  0.4682568757530248
I migliori parametri:  {'alpha': 0.2, 'fit_intercept': True, 'normalize': False}
In [36]:
lasso_r = Lasso(alpha = 0.2, fit_intercept= True, max_iter = 20000)
lasso_r.fit(X_train, y_train)
predict = lasso_r.predict(X_test)
In [37]:
# calcolo il MSE per il dataset di test
mse_tst = mean_squared_error(y_test, predict)
print(f"Il Mean Squared error del test set è : {mse_tst:.3f}")
Il Mean Squared error del test set è : 0.657
In [38]:
# calcolo punteggio R2 per il dataset di test
r2_tst = r2_score(y_test, predict)
print(f"Il punteggio R2 del test set è : {r2_tst:.3f}")
Il punteggio R2 del test set è : 0.476

RIDGE REGRESSION

In [55]:
from sklearn.linear_model import Ridge

ridge_r = Ridge(alpha = 0.4, fit_intercept= True, normalize= False, max_iter = 20000)
ridge_r.fit(X_train, y_train)
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:155: FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2. Please leave the normalize parameter to its default value to silence this warning. The default behavior of this estimator is to not do any normalization. If normalization is needed please use sklearn.preprocessing.StandardScaler instead.
  FutureWarning,
Ridge(alpha=0.4, max_iter=20000, normalize=False)
In [56]:
predict = ridge_r.predict(X_test)
In [57]:
# calcolo il MSE per il dataset di test
mse_tst = mean_squared_error(y_test, predict)
print(f"Il Mean Squared error del test set è : {mse_tst:.3f}")
Il Mean Squared error del test set è : 0.457
In [58]:
# calcolo punteggio R2 per il dataset di test
r2_tst = r2_score(y_test, predict)
print(f"Il punteggio R2 del test set è : {r2_tst:.3f}")
Il punteggio R2 del test set è : 0.635
In [59]:
ridge_r_parameter = {'alpha': [0.2,0.4,0.6,0.8,1], 'normalize': [True, False], 'fit_intercept': [True, False]}
ridge_r_grid_search = GridSearchCV(Ridge(max_iter = 400000), ridge_r_parameter, cv = 2)
ridge_r_grid_search.fit(X_train, y_train)
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:145: FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2.
If you wish to scale the data, use Pipeline with a StandardScaler in a preprocessing stage. To reproduce the previous behavior:

from sklearn.pipeline import make_pipeline

model = make_pipeline(StandardScaler(with_mean=False), Ridge())

If you wish to pass a sample_weight parameter, you need to pass it as a fit parameter to each step of the pipeline as follows:

kwargs = {s[0] + '__sample_weight': sample_weight for s in model.steps}
model.fit(X, y, **kwargs)

Set parameter alpha to: original_alpha * n_samples. 
  FutureWarning,
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:145: FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2.
If you wish to scale the data, use Pipeline with a StandardScaler in a preprocessing stage. To reproduce the previous behavior:

from sklearn.pipeline import make_pipeline

model = make_pipeline(StandardScaler(with_mean=False), Ridge())

If you wish to pass a sample_weight parameter, you need to pass it as a fit parameter to each step of the pipeline as follows:

kwargs = {s[0] + '__sample_weight': sample_weight for s in model.steps}
model.fit(X, y, **kwargs)

Set parameter alpha to: original_alpha * n_samples. 
  FutureWarning,
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:155: FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2. Please leave the normalize parameter to its default value to silence this warning. The default behavior of this estimator is to not do any normalization. If normalization is needed please use sklearn.preprocessing.StandardScaler instead.
  FutureWarning,
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:155: FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2. Please leave the normalize parameter to its default value to silence this warning. The default behavior of this estimator is to not do any normalization. If normalization is needed please use sklearn.preprocessing.StandardScaler instead.
  FutureWarning,
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:145: FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2.
If you wish to scale the data, use Pipeline with a StandardScaler in a preprocessing stage. To reproduce the previous behavior:

from sklearn.pipeline import make_pipeline

model = make_pipeline(StandardScaler(with_mean=False), Ridge())

If you wish to pass a sample_weight parameter, you need to pass it as a fit parameter to each step of the pipeline as follows:

kwargs = {s[0] + '__sample_weight': sample_weight for s in model.steps}
model.fit(X, y, **kwargs)

Set parameter alpha to: original_alpha * n_samples. 
  FutureWarning,
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:145: FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2.
If you wish to scale the data, use Pipeline with a StandardScaler in a preprocessing stage. To reproduce the previous behavior:

from sklearn.pipeline import make_pipeline

model = make_pipeline(StandardScaler(with_mean=False), Ridge())

If you wish to pass a sample_weight parameter, you need to pass it as a fit parameter to each step of the pipeline as follows:

kwargs = {s[0] + '__sample_weight': sample_weight for s in model.steps}
model.fit(X, y, **kwargs)

Set parameter alpha to: original_alpha * n_samples. 
  FutureWarning,
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:155: FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2. Please leave the normalize parameter to its default value to silence this warning. The default behavior of this estimator is to not do any normalization. If normalization is needed please use sklearn.preprocessing.StandardScaler instead.
  FutureWarning,
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:155: FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2. Please leave the normalize parameter to its default value to silence this warning. The default behavior of this estimator is to not do any normalization. If normalization is needed please use sklearn.preprocessing.StandardScaler instead.
  FutureWarning,
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:145: FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2.
If you wish to scale the data, use Pipeline with a StandardScaler in a preprocessing stage. To reproduce the previous behavior:

from sklearn.pipeline import make_pipeline

model = make_pipeline(StandardScaler(with_mean=False), Ridge())

If you wish to pass a sample_weight parameter, you need to pass it as a fit parameter to each step of the pipeline as follows:

kwargs = {s[0] + '__sample_weight': sample_weight for s in model.steps}
model.fit(X, y, **kwargs)

Set parameter alpha to: original_alpha * n_samples. 
  FutureWarning,
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:145: FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2.
If you wish to scale the data, use Pipeline with a StandardScaler in a preprocessing stage. To reproduce the previous behavior:

from sklearn.pipeline import make_pipeline

model = make_pipeline(StandardScaler(with_mean=False), Ridge())

If you wish to pass a sample_weight parameter, you need to pass it as a fit parameter to each step of the pipeline as follows:

kwargs = {s[0] + '__sample_weight': sample_weight for s in model.steps}
model.fit(X, y, **kwargs)

Set parameter alpha to: original_alpha * n_samples. 
  FutureWarning,
/usr/local/lib/python3.7/dist-packages/sklearn/linear_model/_base.py:155: FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2. Please leave the norm
… [output troncato]
GridSearchCV(cv=2, estimator=Ridge(max_iter=400000),
             param_grid={'alpha': [0.2, 0.4, 0.6, 0.8, 1],
                         'fit_intercept': [True, False],
                         'normalize': [True, False]})
In [60]:
print('Il miglior score: ',ridge_r_grid_search.best_score_)
print('I migliori parametri: ',ridge_r_grid_search.best_params_)
Il miglior score:  0.6284113552287464
I migliori parametri:  {'alpha': 0.2, 'fit_intercept': True, 'normalize': False}
In [61]:
ridge_r = Ridge(alpha = 0.2, fit_intercept= True, max_iter = 20000)
ridge_r.fit(X_train, y_train)
predict = ridge_r.predict(X_test)
In [62]:
# calcolo il MSE per il dataset di test
mse_tst = mean_squared_error(y_test, predict)
print(f"Il Mean Squared error del test set è : {mse_tst:.3f}")
Il Mean Squared error del test set è : 0.457
In [63]:
# calcolo punteggio R2 per il dataset di test
r2_tst = r2_score(y_test, predict)
print(f"Il punteggio R2 del test set è : {r2_tst:.3f}")
Il punteggio R2 del test set è : 0.635

ElasticNet

In [75]:
from sklearn.linear_model import ElasticNet

elastic_r = ElasticNet(alpha=0.1, l1_ratio=0.25)
elastic_r.fit(X_train, y_train)
predict = elastic_r.predict(X_test)
In [76]:
elastic_r_parameter = {'alpha': [0.1,0.2,0.4,0.6,0.8,1], 'l1_ratio': [0.25,0.5,0.75,1]}
elastic_r_grid_search = GridSearchCV(ElasticNet(max_iter = 400000), elastic_r_parameter, cv = 2)
elastic_r_grid_search.fit(X_train, y_train)

print('Il miglior score: ',elastic_r_grid_search.best_score_)
print('I migliori parametri: ',elastic_r_grid_search.best_params_)
Il miglior score:  0.5960716408244838
I migliori parametri:  {'alpha': 0.1, 'l1_ratio': 0.25}
In [77]:
# calcolo il MSE per il dataset di test
mse_tst = mean_squared_error(y_test, predict)
print(f"Il Mean Squared error del test set è : {mse_tst:.3f}")
Il Mean Squared error del test set è : 0.493
In [78]:
# calcolo punteggio R2 per il dataset di test
r2_tst = r2_score(y_test, predict)
print(f"Il punteggio R2 del test set è : {r2_tst:.3f}")
Il punteggio R2 del test set è : 0.607