You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

29 KiB

<html> <head> </head>

___

Copyright by Pierian Data Inc. For more information, visit us at www.pieriandata.com

Introduction to Cross Validation

In this lecture series we will do a much deeper dive into various methods of cross-validation. As well as a discussion on the general philosphy behind cross validation. A nice official documentation guide can be found here: https://scikit-learn.org/stable/modules/cross_validation.html

Imports

In [2]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
C:\ProgramData\Anaconda3\lib\site-packages\statsmodels\tools\_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.
  import pandas.util.testing as tm

Data Example

In [3]:
df = pd.read_csv("../DATA/Advertising.csv")
In [4]:
df.head()
Out[4]:
TV radio newspaper sales
0 230.1 37.8 69.2 22.1
1 44.5 39.3 45.1 10.4
2 17.2 45.9 69.3 9.3
3 151.5 41.3 58.5 18.5
4 180.8 10.8 58.4 12.9



Train | Test Split Procedure

  1. Clean and adjust data as necessary for X and y
  2. Split Data in Train/Test for both X and y
  3. Fit/Train Scaler on Training X Data
  4. Scale X Test Data
  5. Create Model
  6. Fit/Train Model on X Train Data
  7. Evaluate Model on X Test Data (by creating predictions and comparing to Y_test)
  8. Adjust Parameters as Necessary and repeat steps 5 and 6
In [5]:
## CREATE X and y
X = df.drop('sales',axis=1)
y = df['sales']

# TRAIN TEST SPLIT
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=101)

# SCALE DATA
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)

Create Model

In [6]:
from sklearn.linear_model import Ridge
In [7]:
# Poor Alpha Choice on purpose!
model = Ridge(alpha=100)
In [8]:
model.fit(X_train,y_train)
Out[8]:
Ridge(alpha=100, copy_X=True, fit_intercept=True, max_iter=None,
      normalize=False, random_state=None, solver='auto', tol=0.001)
In [9]:
y_pred = model.predict(X_test)

Evaluation

In [10]:
from sklearn.metrics import mean_squared_error
In [11]:
mean_squared_error(y_test,y_pred)
Out[11]:
7.34177578903413

Adjust Parameters and Re-evaluate

In [12]:
model = Ridge(alpha=1)
In [13]:
model.fit(X_train,y_train)
Out[13]:
Ridge(alpha=1, copy_X=True, fit_intercept=True, max_iter=None, normalize=False,
      random_state=None, solver='auto', tol=0.001)
In [14]:
y_pred = model.predict(X_test)

Another Evaluation

In [15]:
mean_squared_error(y_test,y_pred)
Out[15]:
2.319021579428752

Much better! We could repeat this until satisfied with performance metrics. (We previously showed RidgeCV can do this for us, but the purpose of this lecture is to generalize the CV process for any model).




Train | Validation | Test Split Procedure

This is often also called a "hold-out" set, since you should not adjust parameters based on the final test set, but instead use it only for reporting final expected performance.

  1. Clean and adjust data as necessary for X and y
  2. Split Data in Train/Validation/Test for both X and y
  3. Fit/Train Scaler on Training X Data
  4. Scale X Eval Data
  5. Create Model
  6. Fit/Train Model on X Train Data
  7. Evaluate Model on X Evaluation Data (by creating predictions and comparing to Y_eval)
  8. Adjust Parameters as Necessary and repeat steps 5 and 6
  9. Get final metrics on Test set (not allowed to go back and adjust after this!)
In [16]:
## CREATE X and y
X = df.drop('sales',axis=1)
y = df['sales']
In [17]:
######################################################################
#### SPLIT TWICE! Here we create TRAIN | VALIDATION | TEST  #########
####################################################################
from sklearn.model_selection import train_test_split

# 70% of data is training data, set aside other 30%
X_train, X_OTHER, y_train, y_OTHER = train_test_split(X, y, test_size=0.3, random_state=101)

# Remaining 30% is split into evaluation and test sets
# Each is 15% of the original data size
X_eval, X_test, y_eval, y_test = train_test_split(X_OTHER, y_OTHER, test_size=0.5, random_state=101)
In [18]:
# SCALE DATA
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_eval = scaler.transform(X_eval)
X_test = scaler.transform(X_test)

Create Model

In [19]:
from sklearn.linear_model import Ridge
In [20]:
# Poor Alpha Choice on purpose!
model = Ridge(alpha=100)
In [21]:
model.fit(X_train,y_train)
Out[21]:
Ridge(alpha=100, copy_X=True, fit_intercept=True, max_iter=None,
      normalize=False, random_state=None, solver='auto', tol=0.001)
In [22]:
y_eval_pred = model.predict(X_eval)

Evaluation

In [23]:
from sklearn.metrics import mean_squared_error
In [24]:
mean_squared_error(y_eval,y_eval_pred)
Out[24]:
7.320101458823871

Adjust Parameters and Re-evaluate

In [25]:
model = Ridge(alpha=1)
In [26]:
model.fit(X_train,y_train)
Out[26]:
Ridge(alpha=1, copy_X=True, fit_intercept=True, max_iter=None, normalize=False,
      random_state=None, solver='auto', tol=0.001)
In [27]:
y_eval_pred = model.predict(X_eval)

Another Evaluation

In [28]:
mean_squared_error(y_eval,y_eval_pred)
Out[28]:
2.383783075056986

Final Evaluation (Can no longer edit parameters after this!)

In [29]:
y_final_test_pred = model.predict(X_test)
In [30]:
mean_squared_error(y_test,y_final_test_pred)
Out[30]:
2.254260083800517



Cross Validation with cross_val_score



In [44]:
## CREATE X and y
X = df.drop('sales',axis=1)
y = df['sales']

# TRAIN TEST SPLIT
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=101)

# SCALE DATA
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
In [45]:
model = Ridge(alpha=100)
In [46]:
from sklearn.model_selection import cross_val_score
In [48]:
# SCORING OPTIONS:
# https://scikit-learn.org/stable/modules/model_evaluation.html
scores = cross_val_score(model,X_train,y_train,
                         scoring='neg_mean_squared_error',cv=5)
In [49]:
scores
Out[49]:
array([ -9.32552967,  -4.9449624 , -11.39665242,  -7.0242106 ,
        -8.38562723])
In [50]:
# Average of the MSE scores (we set back to positive)
abs(scores.mean())
Out[50]:
8.215396464543607

Adjust model based on metrics

In [51]:
model = Ridge(alpha=1)
In [52]:
# SCORING OPTIONS:
# https://scikit-learn.org/stable/modules/model_evaluation.html
scores = cross_val_score(model,X_train,y_train,
                         scoring='neg_mean_squared_error',cv=5)
In [53]:
# Average of the MSE scores (we set back to positive)
abs(scores.mean())
Out[53]:
3.344839296530695

Final Evaluation (Can no longer edit parameters after this!)

In [55]:
# Need to fit the model first!
model.fit(X_train,y_train)
Out[55]:
Ridge(alpha=1, copy_X=True, fit_intercept=True, max_iter=None, normalize=False,
      random_state=None, solver='auto', tol=0.001)
In [56]:
y_final_test_pred = model.predict(X_test)
In [57]:
mean_squared_error(y_test,y_final_test_pred)
Out[57]:
2.319021579428752



Cross Validation with cross_validate

The cross_validate function differs from cross_val_score in two ways:

It allows specifying multiple metrics for evaluation.

It returns a dict containing fit-times, score-times (and optionally training scores as well as fitted estimators) in addition to the test score.

For single metric evaluation, where the scoring parameter is a string, callable or None, the keys will be:

    - ['test_score', 'fit_time', 'score_time']

And for multiple metric evaluation, the return value is a dict with the following keys:

['test_<scorer1_name>', 'test_<scorer2_name>', 'test_<scorer...>', 'fit_time', 'score_time']

return_train_score is set to False by default to save computation time. To evaluate the scores on the training set as well you need to be set to True.

In [62]:
## CREATE X and y
X = df.drop('sales',axis=1)
y = df['sales']

# TRAIN TEST SPLIT
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=101)

# SCALE DATA
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
In [63]:
model = Ridge(alpha=100)
In [64]:
from sklearn.model_selection import cross_validate
In [72]:
# SCORING OPTIONS:
# https://scikit-learn.org/stable/modules/model_evaluation.html
scores = cross_validate(model,X_train,y_train,
                         scoring=['neg_mean_absolute_error','neg_mean_squared_error','max_error'],cv=5)
In [73]:
scores
Out[73]:
{'fit_time': array([0.00102687, 0.00088882, 0.00099993, 0.00099945, 0.        ]),
 'score_time': array([0.00108409, 0.        , 0.        , 0.00064516, 0.00086308]),
 'test_neg_mean_absolute_error': array([-2.31243044, -1.74653361, -2.56211701, -2.01873159, -2.27951906]),
 'test_neg_mean_squared_error': array([ -9.32552967,  -4.9449624 , -11.39665242,  -7.0242106 ,
         -8.38562723]),
 'test_max_error': array([ -6.44988486,  -5.58926073, -10.33914027,  -6.61950405,
         -7.75578515])}
In [74]:
pd.DataFrame(scores)
Out[74]:
fit_time score_time test_neg_mean_absolute_error test_neg_mean_squared_error test_max_error
0 0.001027 0.001084 -2.312430 -9.325530 -6.449885
1 0.000889 0.000000 -1.746534 -4.944962 -5.589261
2 0.001000 0.000000 -2.562117 -11.396652 -10.339140
3 0.000999 0.000645 -2.018732 -7.024211 -6.619504
4 0.000000 0.000863 -2.279519 -8.385627 -7.755785
In [75]:
pd.DataFrame(scores).mean()
Out[75]:
fit_time                        0.000783
score_time                      0.000518
test_neg_mean_absolute_error   -2.183866
test_neg_mean_squared_error    -8.215396
test_max_error                 -7.350715
dtype: float64

Adjust model based on metrics

In [76]:
model = Ridge(alpha=1)
In [77]:
# SCORING OPTIONS:
# https://scikit-learn.org/stable/modules/model_evaluation.html
scores = cross_validate(model,X_train,y_train,
                         scoring=['neg_mean_absolute_error','neg_mean_squared_error','max_error'],cv=5)
In [78]:
pd.DataFrame(scores).mean()
Out[78]:
fit_time                        0.000901
score_time                      0.000200
test_neg_mean_absolute_error   -1.319685
test_neg_mean_squared_error    -3.344839
test_max_error                 -5.161145
dtype: float64

Final Evaluation (Can no longer edit parameters after this!)

In [79]:
# Need to fit the model first!
model.fit(X_train,y_train)
Out[79]:
Ridge(alpha=1, copy_X=True, fit_intercept=True, max_iter=None, normalize=False,
      random_state=None, solver='auto', tol=0.001)
In [80]:
y_final_test_pred = model.predict(X_test)
In [81]:
mean_squared_error(y_test,y_final_test_pred)
Out[81]:
2.319021579428752


</html>