Path: blob/master/Week 4/Programming Assignment - 3/machine-learning-ex3/ex3/ex3_nn.m
865 views
%% Machine Learning Online Class - Exercise 3 | Part 2: Neural Networks12% 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 exercise22input_layer_size = 400; % 20x20 Input Images of Digits23hidden_layer_size = 25; % 25 hidden units24num_labels = 10; % 10 labels, from 1 to 1025% (note that we have mapped "0" to label 10)2627%% =========== Part 1: Loading and Visualizing Data =============28% We start the exercise by first loading and visualizing the dataset.29% You will be working with a dataset that contains handwritten digits.30%3132% Load Training Data33fprintf('Loading and Visualizing Data ...\n')3435load('ex3data1.mat');36m = size(X, 1);3738% Randomly select 100 data points to display39sel = randperm(size(X, 1));40sel = sel(1:100);4142displayData(X(sel, :));4344fprintf('Program paused. Press enter to continue.\n');45pause;4647%% ================ Part 2: Loading Pameters ================48% In this part of the exercise, we load some pre-initialized49% neural network parameters.5051fprintf('\nLoading Saved Neural Network Parameters ...\n')5253% Load the weights into variables Theta1 and Theta254load('ex3weights.mat');5556%% ================= Part 3: Implement Predict =================57% After training the neural network, we would like to use it to predict58% the labels. You will now implement the "predict" function to use the59% neural network to predict the labels of the training set. This lets60% you compute the training set accuracy.6162pred = predict(Theta1, Theta2, X);6364fprintf('\nTraining Set Accuracy: %f\n', mean(double(pred == y)) * 100);6566fprintf('Program paused. Press enter to continue.\n');67pause;6869% To give you an idea of the network's output, you can also run70% through the examples one at the a time to see what it is predicting.7172% Randomly permute examples73rp = randperm(m);7475for i = 1:m76% Display77fprintf('\nDisplaying Example Image\n');78displayData(X(rp(i), :));7980pred = predict(Theta1, Theta2, X(rp(i),:));81fprintf('\nNeural Network Prediction: %d (digit %d)\n', pred, mod(pred, 10));8283% Pause with quit option84s = input('Paused - press enter to continue, q to exit:','s');85if s == 'q'86break87end88end89909192