{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This lab on Ridge Regression and the Lasso is a Python adaptation of p. 251-255 of \"Introduction to Statistical Learning with Applications in R\" by Gareth James, Daniela Witten, Trevor Hastie and Robert Tibshirani. Adapted by R. Jordan Crouser at Smith College for SDS293: Machine Learning (Spring 2016).\n",
"\n",
"# 6.6: Ridge Regression and the Lasso"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline\n",
"\n",
"import pandas as pd\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"\n",
"from sklearn.preprocessing import scale \n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.linear_model import Ridge, RidgeCV, Lasso, LassoCV\n",
"from sklearn.metrics import mean_squared_error"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We will use the `sklearn` package in order to perform ridge regression and\n",
"the lasso. The main functions in this package that we care about are `Ridge()`, which can be used\n",
"to fit ridge regression models, and `Lasso()` which will fit lasso models. They also have cross-validated counterparts: `RidgeCV()` and `LassoCV()`. We'll use these a bit later.\n",
"\n",
"Before proceeding, let's first ensure that the missing values have\n",
"been removed from the data, as described in the previous lab."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"df = pd.read_csv('Hitters.csv').dropna().drop('Player', axis = 1)\n",
"df.info()\n",
"dummies = pd.get_dummies(df[['League', 'Division', 'NewLeague']])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We will now perform ridge regression and the lasso in order to predict `Salary` on\n",
"the `Hitters` data. Let's set up our data:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"y = df.Salary\n",
"\n",
"# Drop the column with the independent variable (Salary), and columns for which we created dummy variables\n",
"X_ = df.drop(['Salary', 'League', 'Division', 'NewLeague'], axis = 1).astype('float64')\n",
"\n",
"# Define the feature set X.\n",
"X = pd.concat([X_, dummies[['League_N', 'Division_W', 'NewLeague_N']]], axis = 1)\n",
"\n",
"X.info()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 6.6.1 Ridge Regression\n",
"The `Ridge()` function has an alpha argument ($\\lambda$, but with a different name!) that is used to tune the model. We'll generate an array of alpha values ranging from very big to very small, essentially\n",
"covering the full range of scenarios from the null model containing\n",
"only the intercept, to the least squares fit:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"alphas = 10**np.linspace(10,-2,100)*0.5\n",
"alphas"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Associated with each alpha value is a vector of ridge regression coefficients, which we'll\n",
"store in a matrix `coefs`. In this case, it is a $19 \\times 100$\n",
"matrix, with 19 rows (one for each predictor) and 100\n",
"columns (one for each value of alpha). Remember that we'll want to standardize the\n",
"variables so that they are on the same scale. To do this, we can use the\n",
"`normalize = True` parameter:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"ridge = Ridge(normalize = True)\n",
"coefs = []\n",
"\n",
"for a in alphas:\n",
" ridge.set_params(alpha = a)\n",
" ridge.fit(X, y)\n",
" coefs.append(ridge.coef_)\n",
" \n",
"np.shape(coefs)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We expect the coefficient estimates to be much smaller, in terms of $l_2$ norm,\n",
"when a large value of alpha is used, as compared to when a small value of alpha is\n",
"used. Let's plot and find out:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"ax = plt.gca()\n",
"ax.plot(alphas, coefs)\n",
"ax.set_xscale('log')\n",
"plt.axis('tight')\n",
"plt.xlabel('alpha')\n",
"plt.ylabel('weights')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We now split the samples into a training set and a test set in order\n",
"to estimate the test error of ridge regression and the lasso:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# Split data into training and test sets\n",
"X_train, X_test , y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next we fit a ridge regression model on the training set, and evaluate\n",
"its MSE on the test set, using $\\lambda = 4$:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"ridge2 = Ridge(alpha = 4, normalize = True)\n",
"ridge2.fit(X_train, y_train) # Fit a ridge regression on the training data\n",
"pred2 = ridge2.predict(X_test) # Use this model to predict the test data\n",
"print(pd.Series(ridge2.coef_, index = X.columns)) # Print coefficients\n",
"print(mean_squared_error(y_test, pred2)) # Calculate the test MSE"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The test MSE when alpha = 4 is 106216. Now let's see what happens if we use a huge value of alpha, say $10^{10}$:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"ridge3 = Ridge(alpha = 10**10, normalize = True)\n",
"ridge3.fit(X_train, y_train) # Fit a ridge regression on the training data\n",
"pred3 = ridge3.predict(X_test) # Use this model to predict the test data\n",
"print(pd.Series(ridge3.coef_, index = X.columns)) # Print coefficients\n",
"print(mean_squared_error(y_test, pred3)) # Calculate the test MSE"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This big penalty shrinks the coefficients to a very large degree, essentially reducing to a model containing just the intercept. This over-shrinking makes the model more biased, resulting in a higher MSE."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Okay, so fitting a ridge regression model with alpha = 4 leads to a much lower test\n",
"MSE than fitting a model with just an intercept. We now check whether\n",
"there is any benefit to performing ridge regression with alpha = 4 instead of\n",
"just performing least squares regression. Recall that least squares is simply\n",
"ridge regression with alpha = 0."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"ridge2 = Ridge(alpha = 0, normalize = True)\n",
"ridge2.fit(X_train, y_train) # Fit a ridge regression on the training data\n",
"pred = ridge2.predict(X_test) # Use this model to predict the test data\n",
"print(pd.Series(ridge2.coef_, index = X.columns)) # Print coefficients\n",
"print(mean_squared_error(y_test, pred)) # Calculate the test MSE"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It looks like we are indeed improving over regular least-squares!\n",
"\n",
"Instead of arbitrarily choosing alpha $ = 4$, it would be better to\n",
"use cross-validation to choose the tuning parameter alpha. We can do this using\n",
"the cross-validated ridge regression function, `RidgeCV()`. By default, the function\n",
"performs generalized cross-validation (an efficient form of LOOCV), though this can be changed using the\n",
"argument `cv`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"ridgecv = RidgeCV(alphas = alphas, scoring = 'neg_mean_squared_error', normalize = True)\n",
"ridgecv.fit(X_train, y_train)\n",
"ridgecv.alpha_"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Therefore, we see that the value of alpha that results in the smallest cross-validation\n",
"error is 0.57. What is the test MSE associated with this value of\n",
"alpha?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"ridge4 = Ridge(alpha = ridgecv.alpha_, normalize = True)\n",
"ridge4.fit(X_train, y_train)\n",
"mean_squared_error(y_test, ridge4.predict(X_test))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This represents a further improvement over the test MSE that we got using\n",
"alpha $ = 4$. Finally, we refit our ridge regression model on the full data set,\n",
"using the value of alpha chosen by cross-validation, and examine the coefficient\n",
"estimates."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"ridge4.fit(X, y)\n",
"pd.Series(ridge4.coef_, index = X.columns)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As expected, none of the coefficients are exactly zero - ridge regression does not\n",
"perform variable selection!\n",
"\n",
"# 6.6.2 The Lasso\n",
"We saw that ridge regression with a wise choice of alpha can outperform least\n",
"squares as well as the null model on the Hitters data set. We now ask\n",
"whether the lasso can yield either a more accurate or a more interpretable\n",
"model than ridge regression. In order to fit a lasso model, we'll\n",
"use the `Lasso()` function; however, this time we'll need to include the argument `max_iter = 10000`.\n",
"Other than that change, we proceed just as we did in fitting a ridge model:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"lasso = Lasso(max_iter = 10000, normalize = True)\n",
"coefs = []\n",
"\n",
"for a in alphas:\n",
" lasso.set_params(alpha=a)\n",
" lasso.fit(scale(X_train), y_train)\n",
" coefs.append(lasso.coef_)\n",
" \n",
"ax = plt.gca()\n",
"ax.plot(alphas*2, coefs)\n",
"ax.set_xscale('log')\n",
"plt.axis('tight')\n",
"plt.xlabel('alpha')\n",
"plt.ylabel('weights')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notice that in the coefficient plot that depending on the choice of tuning\n",
"parameter, some of the coefficients are exactly equal to zero. We now\n",
"perform 10-fold cross-validation to choose the best alpha, refit the model, and compute the associated test error:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"lassocv = LassoCV(alphas = None, cv = 10, max_iter = 100000, normalize = True)\n",
"lassocv.fit(X_train, y_train)\n",
"\n",
"lasso.set_params(alpha=lassocv.alpha_)\n",
"lasso.fit(X_train, y_train)\n",
"mean_squared_error(y_test, lasso.predict(X_test))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This is substantially lower than the test set MSE of the null model and of\n",
"least squares, and only a little worse than the test MSE of ridge regression with alpha\n",
"chosen by cross-validation.\n",
"\n",
"However, the lasso has a substantial advantage over ridge regression in\n",
"that the resulting coefficient estimates are sparse. Here we see that 13 of\n",
"the 19 coefficient estimates are exactly zero:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Some of the coefficients are now reduced to exactly zero.\n",
"pd.Series(lasso.coef_, index=X.columns)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Your turn!\n",
"Now it's time to test out these approaches (ridge regression and the lasso) and evaluation methods (validation set, cross validation) on other datasets. You may want to work with a team on this portion of the lab.\n",
"You may use any of the datasets included in ISLR, or choose one from the UCI machine learning repository (http://archive.ics.uci.edu/ml/datasets.html). Download a dataset, and try to determine the optimal set of parameters to use to model it! You are free to use the same dataset you used in Lab 9, or you can choose a new one."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# Your code here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To get credit for this lab, post your responses to the following questions:\n",
" - Which dataset did you choose?\n",
" - What was your response variable (i.e. what were you trying to model)?\n",
" - Did you expect ridge regression to outperform the lasso, or vice versa?\n",
" - Which predictors turned out to be important in the final model(s)?\n",
" \n",
"to Moodle: https://moodle.smith.edu/mod/quiz/view.php?id=259464"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.0"
}
},
"nbformat": 4,
"nbformat_minor": 0
}