Path: blob/master/1_Supervised_Machine_Learning/Week 2. Regression with multiple input variables/C1_W2_Lab03_Feature_Scaling_and_Learning_Rate_Soln.ipynb
3240 views
Optional Lab: Feature scaling and Learning Rate (Multi-variable)
Goals
In this lab you will:
- Utilize the multiple variables routines developed in the previous lab 
- run Gradient Descent on a data set with multiple features 
- explore the impact of the learning rate alpha on gradient descent 
- improve performance of gradient descent by feature scaling using z-score normalization 
Tools
You will utilize the functions developed in the last lab as well as matplotlib and NumPy.
Notation
|General 
  Notation  | Description| Python (if applicable) | |: ------------|: ------------------------------------------------------------|| |  | scalar, non bold                                                      || |  | vector, bold                                                 || |  | matrix, bold capital                                         || | Regression |         |    |     | |   | training example maxtrix                  | X_train |
|    | training example  targets                | y_train  |  ,  | Training Example | X[i], y[i]| | m | number of training examples | m| | n | number of features in each example | n| |    |  parameter: weight,                       | w    | |             |  parameter: bias                                           | b    |
|  | The result of the model evaluation at   parameterized by :   | f_wb |  || the gradient or partial derivative of cost with respect to a parameter  |dj_dw[j]|  || the gradient or partial derivative of cost with respect to a parameter | dj_db|
Problem Statement
As in the previous labs, you will use the motivating example of housing price prediction. The training data set contains many examples with 4 features (size, bedrooms, floors and age) shown in the table below. Note, in this lab, the Size feature is in sqft while earlier labs utilized 1000 sqft. This data set is larger than the previous lab.
We would like to build a linear regression model using these values so we can then predict the price for other houses - say, a house with 1200 sqft, 3 bedrooms, 1 floor, 40 years old.
Dataset:
| Size (sqft) | Number of Bedrooms | Number of floors | Age of Home | Price (1000s dollars) | 
|---|---|---|---|---|
| 952 | 2 | 1 | 65 | 271.5 | 
| 1244 | 3 | 2 | 64 | 232 | 
| 1947 | 3 | 2 | 17 | 509.8 | 
| ... | ... | ... | ... | ... | 
Let's view the dataset and its features by plotting each feature versus price.
Plotting each feature vs. the target, price, provides some indication of which features have the strongest influence on price. Above, increasing size also increases price. Bedrooms and floors don't seem to have a strong impact on price. Newer houses have higher prices than older houses.
Gradient Descent With Multiple Variables
Here are the equations you developed in the last lab on gradient descent for multiple variables.:
where, n is the number of features, parameters , , are updated simultaneously and where
- m is the number of training examples in the data set 
- is the model's prediction, while is the target value 
Learning Rate
 
Let's run gradient descent and try a few settings of on our data set
= 9.9e-7
It appears the learning rate is too high. The solution does not converge. Cost is increasing rather than decreasing. Let's plot the result:
The plot on the right shows the value of one of the parameters, . At each iteration, it is overshooting the optimal value and as a result, cost ends up increasing rather than approaching the minimum. Note that this is not a completely accurate picture as there are 4 parameters being modified each pass rather than just one. This plot is only showing with the other parameters fixed at benign values. In this and later plots you may notice the blue and orange lines being slightly off.
= 9e-7
Let's try a bit smaller value and see what happens.
Cost is decreasing throughout the run showing that alpha is not too large.
On the left, you see that cost is decreasing as it should. On the right, you can see that  is still oscillating around the minimum, but it is decreasing each iteration rather than increasing. Note above that dj_dw[0] changes sign with each iteration as w[0] jumps over the optimal value. This alpha value will converge. You can vary the number of iterations to see how it behaves.
= 1e-7
Let's try a bit smaller value for and see what happens.
Cost is decreasing throughout the run showing that is not too large.
On the left, you see that cost is decreasing as it should. On the right you can see that  is decreasing without crossing the minimum. Note above that dj_w0 is negative throughout the run. This solution will also converge, though not quite as quickly as the previous example.
Feature Scaling
 
The lectures discussed three different techniques:
- Feature scaling, essentially dividing each positive feature by its maximum value, or more generally, rescale each feature by both its minimum and maximum values using (x-min)/(max-min). Both ways normalizes features to the range of -1 and 1, where the former method works for positive features which is simple and serves well for the lecture's example, and the latter method works for any features. 
- Mean normalization: 
- Z-score normalization which we will explore below. 
z-score normalization
After z-score normalization, all features will have a mean of 0 and a standard deviation of 1.
To implement z-score normalization, adjust your input values as shown in this formula: where selects a feature or a column in the matrix. is the mean of all the values for feature (j) and is the standard deviation of feature (j).
Implementation Note: When normalizing the features, it is important to store the values used for normalization - the mean value and the standard deviation used for the computations. After learning the parameters from the model, we often want to predict the prices of houses we have not seen before. Given a new x value (living room area and number of bed- rooms), we must first normalize x using the mean and standard deviation that we had previously computed from the training set.
Implementation
Let's look at the steps involved in Z-score normalization. The plot below shows the transformation step by step.
The plot above shows the relationship between two of the training set parameters, "age" and "size(sqft)". These are plotted with equal scale.
- Left: Unnormalized: The range of values or the variance of the 'size(sqft)' feature is much larger than that of age 
- Middle: The first step removes the mean or average value from each feature. This leaves features that are centered around zero. It's difficult to see the difference for the 'age' feature, but 'size(sqft)' is clearly around zero. 
- Right: The second step divides by the variance. This leaves both features centered at zero with a similar scale. 
Let's normalize the data and compare it to the original data.
The peak to peak range of each column is reduced from a factor of thousands to a factor of 2-3 by normalization.
Notice, above, the range of the normalized data (x-axis) is centered around zero and roughly +/- 2. Most importantly, the range is similar for each feature.
Let's re-run our gradient descent algorithm with normalized data. Note the vastly larger value of alpha. This will speed up gradient descent.
The scaled features get very accurate results much, much faster!. Notice the gradient of each parameter is tiny by the end of this fairly short run. A learning rate of 0.1 is a good start for regression with normalized features. Let's plot our predictions versus the target values. Note, the prediction is made using the normalized feature while the plot is shown using the original feature values.
The results look good. A few points to note:
- with multiple features, we can no longer have a single plot showing results versus features. 
- when generating the plot, the normalized features were used. Any predictions using the parameters learned from a normalized training set must also be normalized. 
Prediction The point of generating our model is to use it to predict housing prices that are not in the data set. Let's predict the price of a house with 1200 sqft, 3 bedrooms, 1 floor, 40 years old. Recall, that you must normalize the data with the mean and standard deviation derived when the training data was normalized.
Cost Contours
 Another way to view feature scaling is in terms of the cost contours. When feature scales do not match, the plot of cost versus parameters in a contour plot is asymmetric.
Another way to view feature scaling is in terms of the cost contours. When feature scales do not match, the plot of cost versus parameters in a contour plot is asymmetric. 
In the plot below, the scale of the parameters is matched. The left plot is the cost contour plot of w[0], the square feet versus w[1], the number of bedrooms before normalizing the features. The plot is so asymmetric, the curves completing the contours are not visible. In contrast, when the features are normalized, the cost contour is much more symmetric. The result is that updates to parameters during gradient descent can make equal progress for each parameter.
Congratulations!
In this lab you:
- utilized the routines for linear regression with multiple features you developed in previous labs 
- explored the impact of the learning rate on convergence 
- discovered the value of feature scaling using z-score normalization in speeding convergence 
Acknowledgments
The housing data was derived from the Ames Housing dataset compiled by Dean De Cock for use in data science education.