Path: blob/master/Week 4/Programming Assignment - 3/machine-learning-ex3/ex3/ex3.m
864 views
%% Machine Learning Online Class - Exercise 3 | Part 1: One-vs-all12% Instructions3% ------------4%5% This file contains code that helps you get started on the6% linear exercise. You will need to complete the following functions7% in this exericse:8%9% lrCostFunction.m (logistic regression cost function)10% oneVsAll.m11% predictOneVsAll.m12% predict.m13%14% For this exercise, you will not need to change any code in this file,15% or any other files other than those mentioned above.16%1718%% Initialization19clear ; close all; clc2021%% Setup the parameters you will use for this part of the exercise22input_layer_size = 400; % 20x20 Input Images of Digits23num_labels = 10; % 10 labels, from 1 to 1024% (note that we have mapped "0" to label 10)2526%% =========== Part 1: Loading and Visualizing Data =============27% We start the exercise by first loading and visualizing the dataset.28% You will be working with a dataset that contains handwritten digits.29%3031% Load Training Data32fprintf('Loading and Visualizing Data ...\n')3334load('ex3data1.mat'); % training data stored in arrays X, y35m = size(X, 1);3637% Randomly select 100 data points to display38rand_indices = randperm(m);39sel = X(rand_indices(1:100), :);4041displayData(sel);4243fprintf('Program paused. Press enter to continue.\n');44pause;4546%% ============ Part 2a: Vectorize Logistic Regression ============47% In this part of the exercise, you will reuse your logistic regression48% code from the last exercise. You task here is to make sure that your49% regularized logistic regression implementation is vectorized. After50% that, you will implement one-vs-all classification for the handwritten51% digit dataset.52%5354% Test case for lrCostFunction55fprintf('\nTesting lrCostFunction() with regularization');5657theta_t = [-2; -1; 1; 2];58X_t = [ones(5,1) reshape(1:15,5,3)/10];59y_t = ([1;0;1;0;1] >= 0.5);60lambda_t = 3;61[J grad] = lrCostFunction(theta_t, X_t, y_t, lambda_t);6263fprintf('\nCost: %f\n', J);64fprintf('Expected cost: 2.534819\n');65fprintf('Gradients:\n');66fprintf(' %f \n', grad);67fprintf('Expected gradients:\n');68fprintf(' 0.146561\n -0.548558\n 0.724722\n 1.398003\n');6970fprintf('Program paused. Press enter to continue.\n');71pause;72%% ============ Part 2b: One-vs-All Training ============73fprintf('\nTraining One-vs-All Logistic Regression...\n')7475lambda = 0.1;76[all_theta] = oneVsAll(X, y, num_labels, lambda);7778fprintf('Program paused. Press enter to continue.\n');79pause;808182%% ================ Part 3: Predict for One-Vs-All ================8384pred = predictOneVsAll(all_theta, X);85fprintf ("This is prediction: %f\n",pred);86fprintf('\nTraining Set Accuracy: %f\n', mean(double(pred == y)) * 100);87888990