Skip to content

Commit c7ee8de

Browse files
committed
make some changes to regression - text changes and remove a section
1 parent 54e8bf6 commit c7ee8de

File tree

1 file changed

+8
-145
lines changed

1 file changed

+8
-145
lines changed

lessons/01_regression.ipynb

+8-145
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
"\n",
2020
"We're going to use the [Auto MPG dataset](https://archive.ics.uci.edu/ml/datasets/Auto+MPG) from UCI's machine learning repository. The Auto MPG dataset contains information on city-cycle fuel consumption in miles per gallon for various types of cars. Our goal is to predict the miles per gallon of different car make and models using 7 predictors. \n",
2121
"\n",
22-
"The `auto-mpg` dataset is stored in a `.csv` file that can be accessed from the UCI repository. We've obtained a copy and made a few modifications, which we've stored in the `data` folder. We'll use `pandas` to load in the dataset by specifying the correct path. We'll start by performing some exploratory data analysis, and then building an OLS model.\n",
22+
"The `auto-mpg` dataset is stored in a `.csv` file that can be accessed from the UCI repository. We've obtained a copy and made a few modifications, which we've stored in the `data` folder. We'll use `pandas` to load in the dataset by specifying the correct path. We'll start by performing some exploratory data analysis, and then build an OLS model.\n",
2323
"\n",
2424
"First, let's import (or install) some packages we'll need."
2525
]
@@ -144,7 +144,7 @@
144144
"cell_type": "markdown",
145145
"metadata": {},
146146
"source": [
147-
"Some variables are pretty strongly correlated with miles per game, so there may be some predictive signal here."
147+
"Some variables are pretty strongly correlated with miles per gallon, so there may be some predictive signal here."
148148
]
149149
},
150150
{
@@ -172,7 +172,7 @@
172172
"source": [
173173
"## Creating Train and Test Splits\n",
174174
"\n",
175-
"Next, we'll want to split our dataset into `train` and `test` data. When creating the model, we need to make sure it only sees the training data. Then, we can examine how well it **generalizes** to data it hasn't seen before. The train and test split is a foundational concept in machine learning. Be sure you're confident you understand why we do this before moving forward!\n",
175+
"Next, we'll want to split our dataset into training and test data. When creating the model, we need to make sure it only sees the training data. Then, we can examine how well it **generalizes** to data it hasn't seen before. The train and test split is a foundational concept in machine learning. Be sure you're confident you understand why we do this before moving forward!\n",
176176
"\n",
177177
"A dataset is often broken up into a feature set, or **design matrix** (typically with the variable name `X`) as well as the target or response variable `y`. Both have $D$ samples, but the design matrix will have a second dimension indicating the number of features we're using for prediction.\n",
178178
"\n",
@@ -198,7 +198,7 @@
198198
"cell_type": "markdown",
199199
"metadata": {},
200200
"source": [
201-
"Now, we perform the train/test split. The package `scikit-learn` provides a function we can easily use to perform this split. Let's import it:"
201+
"Now, we perform the train/test split. The package `scikit-learn` is the most commonly used package for machine learning in Python. It provides a function we can easily use to perform this split. Let's import it:"
202202
]
203203
},
204204
{
@@ -260,7 +260,7 @@
260260
"cell_type": "markdown",
261261
"metadata": {},
262262
"source": [
263-
"## What is Ordinary Least Squares?\n",
263+
"### What is Ordinary Least Squares?\n",
264264
"\n",
265265
"At a high level, linear regression is nothing more than finding the best straight line, or line of best fit through a set of data points that most accurately captures the pattern that exists within those data points.\n",
266266
"\n",
@@ -291,7 +291,7 @@
291291
"\n",
292292
"The goal of linear regression, then, is to find a combination of these $\\beta_i$ values such that we pass through or as close to as many data points as possible. In other words, we are trying to find the values of $\\beta$ that reduce or minimize the aggregate distance between our linear model and the data points. \n",
293293
"\n",
294-
"We can formalize this into an optimization problem and pursue a strategy that is known in machine learning as minimizing the **cost function** or **objective function**. In the case of linear regression, the cost function we are trying to minimize is the **mean squared error (MSE)** function:\n",
294+
"We can formalize this into an optimization problem and pursue a strategy that is known in machine learning as minimizing the **cost function** or **objective function** or **loss**. In the case of linear regression, the cost function we are trying to minimize is the **mean squared error (MSE)** function:\n",
295295
"\n",
296296
"$$\\text{MSE} = \\frac{1}{N}\\sum_{i=1}^{N}(y_i - \\hat{y}_i)^2$$\n",
297297
"\n",
@@ -317,7 +317,7 @@
317317
"## OLS in Practice\n",
318318
"\n",
319319
"The package `scikit-learn` makes it very easy to train a linear regression model. In general, `scikit-learn` models follow the same structure:\n",
320-
"* Import the model you want to train (here, `LinearRegression`)\n",
320+
"* Import the model you want to train (here, `LinearRegression`).\n",
321321
"* Create an object for that model with chosen settings. This is *not* training the model. For example, in linear regression, you may choose a linear regression object that does or does not fit an intercept term (see the [documentation](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html#sklearn.linear_model.LinearRegression) for more details).\n",
322322
"* Train the model using the `fit()` function, passing in the training data.\n",
323323
"* Evaluate the model on new data using the `predict()` and `score()` functions.\n",
@@ -372,7 +372,7 @@
372372
"\n",
373373
"When evaluating models, it's helpful to look at how it performs on both the training and test data, separately. This gives us a sense of the generalization gap, or how much we overfit to our data. If that gap is large, that means we need to make adjustments to the model in order to make sure it learns patterns that generalize well. \n",
374374
"\n",
375-
"For regression models, the `.score()` method returns the amount of variance in the output variable that can be explained by the model predictions. This is known as $R^2$, or R-squared. It varies from 0 to 1, with 1 being better predictive performance. There are many other performance metrics that can be used when predicting continuous variables.\n",
375+
"For regression models, the `score()` method returns the amount of variance in the output variable that can be explained by the model predictions. This is known as $R^2$, or R-squared. It has a maximum of 1, with 1 being better predictive performance. There are many other performance metrics that can be used when predicting continuous variables.\n",
376376
"\n",
377377
"Let's look at the $R^2$ for the training data:"
378378
]
@@ -498,143 +498,6 @@
498498
"# YOUR CODE HERE\n"
499499
]
500500
},
501-
{
502-
"cell_type": "markdown",
503-
"metadata": {},
504-
"source": [
505-
"\n",
506-
"For linear regression models, one form of regularization is known as **Ridge (L2) regression**. Instead of using the least squares loss (which is the loss function used to calculate our MSE cost function): \n",
507-
"$$ L(\\beta) = \\sum_i^n (y_i - \\hat y_i)^2 $$ \n",
508-
"\n",
509-
"In ridge regression we additionally penalize the coefficients by adding a regularization term: \n",
510-
"\n",
511-
"$$ L(\\beta) = \\sum_i^n (y_i - \\hat y_i)^2 + \\alpha \\sum_j^p \\beta^2 $$ \n",
512-
"\n",
513-
"This regularization term aims to minimize the size of any one coefficient (or weight), penalizing any reliance on a given subset of features which commonly leads to overfitting.\n",
514-
"\n",
515-
"Ridge regression takes a **hyperparameter**, called alpha, $\\alpha$ (sometimes lambda, $\\lambda$). This hyperparameter indicates how much regularization should be done. In other words, how much to care about the coefficient penalty term vs how much to care about the sum of squared errors term. The higher the value of alpha the more regularization, and the smaller the resulting coefficients will be. See [here](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Ridge.html#sklearn.linear_model.Ridge) for more. \n",
516-
"\n",
517-
"If we use an `alpha` value of `0` then we get the same solution as the OLS regression done above. Let's prove that."
518-
]
519-
},
520-
{
521-
"cell_type": "code",
522-
"execution_count": null,
523-
"metadata": {},
524-
"outputs": [],
525-
"source": [
526-
"from sklearn.linear_model import Ridge\n",
527-
"ridge_reg = Ridge(alpha=0, # regularization\n",
528-
" solver='auto',\n",
529-
" random_state = rand_seed) \n",
530-
"ridge_reg.fit(X_train, y_train)\n",
531-
"\n",
532-
"# Predictions\n",
533-
"ridge_train_pred = ridge_reg.predict(X_train)\n",
534-
"ridge_test_pred = ridge_reg.predict(X_test)"
535-
]
536-
},
537-
{
538-
"cell_type": "code",
539-
"execution_count": null,
540-
"metadata": {},
541-
"outputs": [],
542-
"source": [
543-
"print('Train RMSE: %.04f' % (mse(y_train, ridge_train_pred, squared=False)))\n",
544-
"print('Test RMSE: %.04f' % (mse(y_test, ridge_test_pred, squared=False)))"
545-
]
546-
},
547-
{
548-
"cell_type": "markdown",
549-
"metadata": {},
550-
"source": [
551-
"Generally we don't know what the best value hypterparameter values should be, and so we need to leverage some type of trial and error method to determine the best values. We won't cover it today (it's covered in detail on Day 2), but scikit-learn provides a `RidgeCV` model that does just that. It fits a ridge regression model by first using cross-validation to find a good value of alpha. See [here](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.RidgeCV.html#sklearn.linear_model.RidgeCV) for more."
552-
]
553-
},
554-
{
555-
"cell_type": "markdown",
556-
"metadata": {},
557-
"source": [
558-
"Just for our sanity, let's see if we can improve on our baseline linear regression model using a ridge model by setting our alpha value to 0.1."
559-
]
560-
},
561-
{
562-
"cell_type": "code",
563-
"execution_count": null,
564-
"metadata": {},
565-
"outputs": [],
566-
"source": [
567-
"ridge_reg = Ridge(alpha=0.1, # regularization\n",
568-
" solver='auto',\n",
569-
" random_state = rand_seed) \n",
570-
"ridge_reg.fit(X_train, y_train)\n",
571-
"\n",
572-
"# Predictions\n",
573-
"ridge_train_pred = ridge_reg.predict(X_train)\n",
574-
"ridge_test_pred = ridge_reg.predict(X_test)"
575-
]
576-
},
577-
{
578-
"cell_type": "code",
579-
"execution_count": null,
580-
"metadata": {},
581-
"outputs": [],
582-
"source": [
583-
"print('Train RMSE: %.04f' % (mse(y_train, ridge_train_pred, squared=False)))\n",
584-
"print('Test RMSE: %.04f' % (mse(y_test, ridge_test_pred, squared=False)))"
585-
]
586-
},
587-
{
588-
"cell_type": "markdown",
589-
"metadata": {},
590-
"source": [
591-
"Looks like despite doing slightly worse on the training set, it did a bit better than using regular OLS on the test set!"
592-
]
593-
},
594-
{
595-
"cell_type": "code",
596-
"execution_count": null,
597-
"metadata": {},
598-
"outputs": [],
599-
"source": [
600-
"from sklearn.linear_model import Lasso\n",
601-
"lasso_reg = Lasso(alpha=0.01, # regularization\n",
602-
" random_state = rand_seed) \n",
603-
"lasso_reg.fit(X_train, y_train)\n",
604-
"\n",
605-
"# Predictions\n",
606-
"lasso_train_pred = lasso_reg.predict(X_train)\n",
607-
"lasso_test_pred = lasso_reg.predict(X_test)"
608-
]
609-
},
610-
{
611-
"cell_type": "code",
612-
"execution_count": null,
613-
"metadata": {},
614-
"outputs": [],
615-
"source": [
616-
"print('Train RMSE: %.04f' % (mse(y_train, lasso_train_pred, squared=False)))\n",
617-
"print('Test RMSE: %.04f' % (mse(y_test, lasso_test_pred, squared=False)))"
618-
]
619-
},
620-
{
621-
"cell_type": "markdown",
622-
"metadata": {},
623-
"source": [
624-
"In this case, we can see that even with a small alpha, we have too much regularization which leads to worse performance on both train and test datasets. In this case, we would call our model **underfit**.\n",
625-
"\n",
626-
"Taking a look at our feature coeffiecients, we can see that many of them are 0:"
627-
]
628-
},
629-
{
630-
"cell_type": "code",
631-
"execution_count": null,
632-
"metadata": {},
633-
"outputs": [],
634-
"source": [
635-
"lasso_reg.coef_"
636-
]
637-
},
638501
{
639502
"cell_type": "markdown",
640503
"metadata": {},

0 commit comments

Comments
 (0)