Path: blob/master/Week 6/Programming Assignment - 5/machine-learning-ex5/ex5/ex5.m
864 views
%% Machine Learning Online Class1% Exercise 5 | Regularized Linear Regression and Bias-Variance2%3% Instructions4% ------------5%6% This file contains code that helps you get started on the7% exercise. You will need to complete the following functions:8%9% linearRegCostFunction.m10% learningCurve.m11% validationCurve.m12%13% For this exercise, you will not need to change any code in this file,14% or any other files other than those mentioned above.15%1617%% Initialization18clear ; close all; clc1920%% =========== Part 1: Loading and Visualizing Data =============21% We start the exercise by first loading and visualizing the dataset.22% The following code will load the dataset into your environment and plot23% the data.24%2526% Load Training Data27fprintf('Loading and Visualizing Data ...\n')2829% Load from ex5data1:30% You will have X, y, Xval, yval, Xtest, ytest in your environment31load ('ex5data1.mat');3233% m = Number of examples34m = size(X, 1);3536% Plot training data37plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);38xlabel('Change in water level (x)');39ylabel('Water flowing out of the dam (y)');4041fprintf('Program paused. Press enter to continue.\n');42pause;4344%% =========== Part 2: Regularized Linear Regression Cost =============45% You should now implement the cost function for regularized linear46% regression.47%4849theta = [1 ; 1];50J = linearRegCostFunction([ones(m, 1) X], y, theta, 1);5152fprintf(['Cost at theta = [1 ; 1]: %f '...53'\n(this value should be about 303.993192)\n'], J);5455fprintf('Program paused. Press enter to continue.\n');56pause;5758%% =========== Part 3: Regularized Linear Regression Gradient =============59% You should now implement the gradient for regularized linear60% regression.61%6263theta = [1 ; 1];64[J, grad] = linearRegCostFunction([ones(m, 1) X], y, theta, 1);6566fprintf(['Gradient at theta = [1 ; 1]: [%f; %f] '...67'\n(this value should be about [-15.303016; 598.250744])\n'], ...68grad(1), grad(2));6970fprintf('Program paused. Press enter to continue.\n');71pause;727374%% =========== Part 4: Train Linear Regression =============75% Once you have implemented the cost and gradient correctly, the76% trainLinearReg function will use your cost function to train77% regularized linear regression.78%79% Write Up Note: The data is non-linear, so this will not give a great80% fit.81%8283% Train linear regression with lambda = 084lambda = 0;85[theta] = trainLinearReg([ones(m, 1) X], y, lambda);8687% Plot fit over the data88plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);89xlabel('Change in water level (x)');90ylabel('Water flowing out of the dam (y)');91hold on;92plot(X, [ones(m, 1) X]*theta, '--', 'LineWidth', 2)93hold off;9495fprintf('Program paused. Press enter to continue.\n');96pause;979899%% =========== Part 5: Learning Curve for Linear Regression =============100% Next, you should implement the learningCurve function.101%102% Write Up Note: Since the model is underfitting the data, we expect to103% see a graph with "high bias" -- Figure 3 in ex5.pdf104%105106lambda = 0;107[error_train, error_val] = ...108learningCurve([ones(m, 1) X], y, ...109[ones(size(Xval, 1), 1) Xval], yval, ...110lambda);111112plot(1:m, error_train, 1:m, error_val);113title('Learning curve for linear regression')114legend('Train', 'Cross Validation')115xlabel('Number of training examples')116ylabel('Error')117axis([0 13 0 150])118119fprintf('# Training Examples\tTrain Error\tCross Validation Error\n');120for i = 1:m121fprintf(' \t%d\t\t%f\t%f\n', i, error_train(i), error_val(i));122end123124fprintf('Program paused. Press enter to continue.\n');125pause;126127%% =========== Part 6: Feature Mapping for Polynomial Regression =============128% One solution to this is to use polynomial regression. You should now129% complete polyFeatures to map each example into its powers130%131132p = 8;133134% Map X onto Polynomial Features and Normalize135X_poly = polyFeatures(X, p);136[X_poly, mu, sigma] = featureNormalize(X_poly); % Normalize137X_poly = [ones(m, 1), X_poly]; % Add Ones138139% Map X_poly_test and normalize (using mu and sigma)140X_poly_test = polyFeatures(Xtest, p);141X_poly_test = bsxfun(@minus, X_poly_test, mu);142X_poly_test = bsxfun(@rdivide, X_poly_test, sigma);143X_poly_test = [ones(size(X_poly_test, 1), 1), X_poly_test]; % Add Ones144145% Map X_poly_val and normalize (using mu and sigma)146X_poly_val = polyFeatures(Xval, p);147X_poly_val = bsxfun(@minus, X_poly_val, mu);148X_poly_val = bsxfun(@rdivide, X_poly_val, sigma);149X_poly_val = [ones(size(X_poly_val, 1), 1), X_poly_val]; % Add Ones150151fprintf('Normalized Training Example 1:\n');152fprintf(' %f \n', X_poly(1, :));153154fprintf('\nProgram paused. Press enter to continue.\n');155pause;156157158159%% =========== Part 7: Learning Curve for Polynomial Regression =============160% Now, you will get to experiment with polynomial regression with multiple161% values of lambda. The code below runs polynomial regression with162% lambda = 0. You should try running the code with different values of163% lambda to see how the fit and learning curve change.164%165166lambda = 0;167[theta] = trainLinearReg(X_poly, y, lambda);168169% Plot training data and fit170figure(1);171plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);172plotFit(min(X), max(X), mu, sigma, theta, p);173xlabel('Change in water level (x)');174ylabel('Water flowing out of the dam (y)');175title (sprintf('Polynomial Regression Fit (lambda = %f)', lambda));176177figure(2);178[error_train, error_val] = ...179learningCurve(X_poly, y, X_poly_val, yval, lambda);180plot(1:m, error_train, 1:m, error_val);181182title(sprintf('Polynomial Regression Learning Curve (lambda = %f)', lambda));183xlabel('Number of training examples')184ylabel('Error')185axis([0 13 0 100])186legend('Train', 'Cross Validation')187188fprintf('Polynomial Regression (lambda = %f)\n\n', lambda);189fprintf('# Training Examples\tTrain Error\tCross Validation Error\n');190for i = 1:m191fprintf(' \t%d\t\t%f\t%f\n', i, error_train(i), error_val(i));192end193194fprintf('Program paused. Press enter to continue.\n');195pause;196197%% =========== Part 8: Validation for Selecting Lambda =============198% You will now implement validationCurve to test various values of199% lambda on a validation set. You will then use this to select the200% "best" lambda value.201%202203[lambda_vec, error_train, error_val] = ...204validationCurve(X_poly, y, X_poly_val, yval);205206close all;207plot(lambda_vec, error_train, lambda_vec, error_val);208legend('Train', 'Cross Validation');209xlabel('lambda');210ylabel('Error');211212fprintf('lambda\t\tTrain Error\tValidation Error\n');213for i = 1:length(lambda_vec)214fprintf(' %f\t%f\t%f\n', ...215lambda_vec(i), error_train(i), error_val(i));216end217218fprintf('Program paused. Press enter to continue.\n');219pause;220221222