Tutorial_06
QBUS2820 – Predictive Analytics
Tutorial 6 – Model Selection and Estimation¶
Copyright By PowCoder代写 加微信 powcoder
Recall that, in Tut 04, we focused on demonstrating the bias-variance decomposition, and in Tut 05 we practiced model selection for kNN.
In Tut 06, we
1) Continue model selection for kNN using alternative built-in CV methods
2) Model selection in linear regression with CV
3) Look at how to implement AIC/BIC for model selection in linear regression
First, let’s use the same approach as the previous weeks to simulate some data
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
# Initialise RNG, so we get same result everytime
np.random.seed(0)
# Number of training points
x = np.linspace(0.0, 1.0, n)
# Function coefficients/parameters
beta1 = 1.5
beta2 = 3.2
# f values from 2nd order polynomial
f = beta0 + beta1 * x + beta2 * np.power(x,2)
$f$ contains data perfectly sampled along the 2nd order polynomial. In the real world we usually observe data that is noisy. So we will add a small amount of Gaussian noise to the data
# Generate noisy sample from population
sigma2 = 0.1
y_train = f + np.random.normal(0, np.sqrt(sigma2), n)
y_validation = f + np.random.normal(0, np.sqrt(sigma2), n)
fig1 = plt.figure()
plt.plot(x, f, label = “f (Ground Truth)”)
plt.scatter(x, y_train, label = “y (Observed Points)”, color = “red”)
plt.scatter(x, y_validation, label = “y (Observed Points)”, color = “orange”, alpha = 0.5)
plt.xlabel(“Predictor/Feature Value”)
plt.ylabel(“Target Value”)
plt.title(“Underlying Function vs Observations”)
plt.legend(loc=”upper left”)
Selecting k in kNN with GridSearchCV¶
GridSearchCV is an exhaustive search over specified hyperparameter values, which is convenient when you have a few hyperparameters to search for the best combination. In kNN, there is only one hyperparameter, which is K.
# GridSearchCV
from sklearn.model_selection import GridSearchCV
from sklearn.neighbors import KNeighborsRegressor
# Set up the grid of parameters to search (in this case its 1 dimensional)
param_grid = {
‘n_neighbors’: np.arange(1,11)
model = KNeighborsRegressor()
# Create the grid search object
grid_cv_obj = GridSearchCV(model, param_grid)
# Do the grid search
grid_cv_obj.fit(x.reshape(-1, 1), y_train)
print(“Grid Search CV Complete!”)
Grid Search CV Complete!
# Get the best model
best_model = grid_cv_obj.best_estimator_
# Print the best model
print(best_model)
KNeighborsRegressor(n_neighbors=3)
# Print the best params
print(grid_cv_obj.best_params_)
{‘n_neighbors’: 3}
import pandas as pd
results = pd.DataFrame(grid_cv_obj.cv_results_)
results.head()
mean_fit_time std_fit_time mean_score_time std_score_time param_n_neighbors params split0_test_score split1_test_score split2_test_score split3_test_score split4_test_score mean_test_score std_test_score rank_test_score
0 0.000200 0.000399 0.000798 0.000399 1 {‘n_neighbors’: 1} -8.929732 -0.576474 0.310622 0.532245 -2.382193 -2.209106 3.513582 10
1 0.000598 0.000489 0.004987 0.009973 2 {‘n_neighbors’: 2} -0.770062 -0.259626 0.312044 0.084440 -2.913159 -0.709273 1.160695 3
2 0.000199 0.000399 0.000798 0.000399 3 {‘n_neighbors’: 3} -0.001987 -0.208055 0.406673 0.099131 -3.425612 -0.625970 1.413798 1
3 0.000200 0.000399 0.000598 0.000489 4 {‘n_neighbors’: 4} -0.012584 -0.094462 0.431051 0.309368 -3.973034 -0.667932 1.664027 2
4 0.000395 0.000484 0.000403 0.000494 5 {‘n_neighbors’: 5} -0.413810 -0.028687 0.387318 0.129809 -4.329343 -0.850943 1.758501 5
Understanding Grid Search¶
In this kNN example we only had one parameter so the grid is just a 1 dimensonal list. GridSearchCV performs cross validation for each value of n_neighbours and returns the best value of n_neighbours.
We can use the ParameterGrid object in sklearn to list out all combinations of values that will be checked. In this case there are only 10.
from sklearn.model_selection import ParameterGrid
grid_df = pd.DataFrame(list(ParameterGrid(param_grid)))
n_neighbors
GridSearchCV is convenient to use when you have a few hyperparameters.
If we have 3 hyperparameters, for example, then the search list is 3-dimensional,
and the number of hyperparameter combinations that we have to search increases dramatically. We perform cross validation for each row in the parameter grid.
Suppose we have three hyperparameters a (integer from 1 to 10), b (integer from 101 to 110) and c (from -4 to 5).
Below we show the first 15 rows from 1000 ($10 \times 10 \times 10$) total rows.
from sklearn.model_selection import ParameterGrid
param_grid = {
‘param_a’: np.arange(1,11),
‘param_b’: np.arange(101,111),
‘param_c’: np.arange(-4,6),
grid_df_3 = pd.DataFrame(list(ParameterGrid(param_grid)))
grid_df_3.head(15)
param_a param_b param_c
0 1 101 -4
1 1 101 -3
2 1 101 -2
3 1 101 -1
10 1 102 -4
11 1 102 -3
12 1 102 -2
13 1 102 -1
14 1 102 0
Total number of combinations of hyperparamters
len(grid_df_3)
CV for linear regression¶
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import mean_squared_error
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
max_deg = 10
cv_scores_lr = []
for i in range(1, max_deg):
poly_transformer = PolynomialFeatures(i)
poly_x = poly_transformer.fit_transform(x.reshape(-1,1))
# Create the linear regression object
lin_reg = LinearRegression()
# use 3-fold cv
# https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_val_score.html
scores_lr = cross_val_score(lin_reg, poly_x, y_train, cv=3, scoring = ‘neg_mean_squared_error’)
# Get the mean of the scores from the 3 folds
cv_score = np.mean(scores_lr)
cv_scores_lr.append(cv_score)
You can change the number of folds in cross validation, and see what is the impact of it on the model selection.¶
cv_scores_lr
[-1.162670652752948,
-0.12018520719369212,
-0.6348203278920471,
-0.4377185231593099,
-55.375380007723244,
-245.9639372138765,
-230.5744968177327,
-59714.60636576532,
-1083140.4322969527]
The optimal Polynomial order
1 + np.argmax(cv_scores_lr)
fig = plt.figure()
plt.plot(np.arange(1,max_deg), cv_scores_lr)
plt.xlabel(“Polynomial Degree”)
plt.ylabel(“CV score (Higher is better)”)
Text(0, 0.5, ‘CV score (Higher is better)’)
Note the in the above plot the extreme values, e.g. -3126766.599, make the pattern of the plot not clear. Let’s only plot CV score versus the first 4 polynomial orders.
fig = plt.figure()
plt.plot(np.arange(1,5), cv_scores_lr[0:4])
plt.xlabel(“Polynomial Degree”)
plt.ylabel(“CV score (Higher is better)”)
Text(0, 0.5, ‘CV score (Higher is better)’)
Using CV to Evaluate Model Performance¶
Lets compare the performance of our best polynomial regression model with that of the knn regressor.
To ensure that each model sees the exact same K-Folds we need to store the K-Fold split in to a Python object and then share it to the cross_val_score function
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
# Build poly2 model
poly_transformer = PolynomialFeatures(2)
poly_x = poly_transformer.fit_transform(x.reshape(-1,1))
poly_reg = LinearRegression()
poly_reg.fit(poly_x, y_train)
# Build knn model
knn = KNeighborsRegressor(n_neighbors= 4)
knn.fit(x.reshape(-1, 1), y_train)
KNeighborsRegressor(n_neighbors=4)
from sklearn.model_selection import KFold
# 3-Fold Cross Validation
kf = KFold(3)
poly_scores = cross_val_score(poly_reg, poly_x, y_train, cv = kf)
poly_mean = np.mean(poly_scores)
knn_scores = cross_val_score(knn, x.reshape(-1,1), y_train, cv = kf)
knn_mean = np.mean(knn_scores)
# Make the results pretty
{“Model”: “Polynomial Regression”, “CV score”: poly_mean},
{“Model”: “KNN Regressor”, “CV score”: knn_mean}
results = pd.DataFrame(data)
results = results.set_index(“Model”)
Polynomial Regression 0.433527
KNN Regressor -2.672823
Model selection with AIC and BIC in linear regression¶
Consider a linear regression model with response vector $y$ and design matrix $X$. Let
$\hat{\sigma^2}=\frac{1}{n}(y-X\widehat\beta)^\top(y-X\widehat\beta)$
be the estimate of the variance of error term $\epsilon$. The AIC and BIC formulas, specific for the gaussian likelihood are given by
$AIC=n\log(\hat{\sigma^2})+2d$
$BIC=n\log(\hat{\sigma^2})+\log(n)d$
with $n$ the data size and $d$ the total number of parameters in the model. Please refer to a question on Ed Discussion for a derivation of these AIC and BIC formula.
Now, let’s create a synthetic dataset as in Tutorial 04 and let’s see how AIC/BIC work as model choice techniques. The data comes from the following model
$y = \beta_0 + \beta_1 x + \beta_2 x^2 +\epsilon,$
and we compare between the following potential models
$y = \beta_0 + \beta_1 x +\epsilon$
$y = \beta_0 + \beta_1 x + \beta_2 x^2 +\epsilon$
$y = \beta_0 + \beta_1 x + \beta_2 x^2 +\beta_3 x^3+\epsilon$
For the $k$-polynomial regression model, the total number od parameters is $d=k+2$ (why?)
import numpy as np
import matplotlib.pyplot as plt
# Initialise RNG, so we get same result everytime
np.random.seed(0)
# Number of training points
x = np.linspace(0.0, 1.0, n)
# true coefficients/parameters
beta1 = 1.5
beta2 = 3.2
# generate data
sigma2 = 0.1
y = beta0 + beta1 * x + beta2 * np.power(x,2) + np.random.normal(0, np.sqrt(sigma2), n)
Calculate AIC and BIC values for the three models
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import mean_squared_error
from sklearn.linear_model import LinearRegression
max_deg = 4
aic = list()
bic = list()
for k in range(1, max_deg):
poly_transformer = PolynomialFeatures(k)
poly_x = poly_transformer.fit_transform(x.reshape(-1,1))
# Create the linear regression object
lin_reg = LinearRegression()
# Estimate coefficients
lin_reg.fit(poly_x, y)
# Calculate predictions
y_pred = lin_reg.predict(poly_x)
# Calcualte sigma2_hat
sigma2_hat = mean_squared_error(y, y_pred)
number_of_parameters = k+2
aic_value = n*np.log(sigma2_hat)+2*number_of_parameters
bic_value = n*np.log(sigma2_hat)+np.log(n)*number_of_parameters
aic.append(aic_value)
bic.append(bic_value)
[-145.12914244244618, -238.13407604531412, -236.15160054620478]
[-137.3136318844819, -227.71339530136174, -223.12574961626433]
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com