Path: blob/master/Week 4/Programming Assignment - 3/machine-learning-ex3/ex3/predict.m
864 views
function p = predict(Theta1, Theta2, X)1%PREDICT Predict the label of an input given a trained neural network2% p = PREDICT(Theta1, Theta2, X) outputs the predicted label of X given the3% trained weights of a neural network (Theta1, Theta2)45% Useful values6m = size(X, 1);7num_labels = size(Theta2, 1);89% You need to return the following variables correctly10p = zeros(size(X, 1), 1);1112% ====================== YOUR CODE HERE ======================13% Instructions: Complete the following code to make predictions using14% your learned neural network. You should set p to a15% vector containing labels between 1 to num_labels.16%17% Hint: The max function might come in useful. In particular, the max18% function can also return the index of the max element, for more19% information see 'help max'. If your examples are in rows, then, you20% can use max(A, [], 2) to obtain the max for each row.21%22a1 = [ones(m,1) X]; %Adding bias-unit to a12324% Step-1: Computing the 2nd activation layer25z2 = a1 * Theta1';26a2 = sigmoid(z2);2728% Step-2: Computing the 3rd activation layer29a2 = [ones(m,1) a2]; %Adding bias-unit to a230z3 = a2 * Theta2';31a3 = sigmoid(z3); %This computes the final hypothesis3233% Step-4: Finding the max prediction and determining its index, to compute...34% the probability at class k, where k =[0:9], represents the digits35[predict index] = max(a3'); % size(a3) = 1 x 500036p = index';37% =========================================================================38end394041