-
Notifications
You must be signed in to change notification settings - Fork 6
/
predictNN.m
58 lines (53 loc) · 1.59 KB
/
predictNN.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
function [p, h] = predictNN(X, varargin)
%PREDICTNN Predict the label of an input given a trained neural network
%
% [p, h] = PREDICTNN(X, Theta, activationFn) outputs the predicted
% label of X given the trained weights of a neural network Theta. This
% option does not normalize the data.
% or
% [p, h] = PREDICTNN(X, modelNN)
% This normalizes the data based on the mu and std in the modelNN
%
% Vahe Tshitoyan
% 26/08/2017
%
% Inputs
% X: The feature matrix to run the prediction on
% Theta: The weights as a cell array modelNN.Theta
% activationFn: 'tanh' or 'sigm'
% modelNN: The trained NN model
%
% Outputs:
% p: The predicted label
% h: The values of the hypotheses for all labels as a vector
if nargin==2
modelNN = varargin{1};
Theta = modelNN.Theta;
activationFn = modelNN.activationFn;
% also need to normalize here
X = (X - repmat(modelNN.nnMu,size(X,1),1))...
./repmat(modelNN.nnSigma,size(X,1),1);
X(isnan(X)) = 0;
elseif nargin==3
Theta = varargin{1};
activationFn = varargin{2};
else
error('predictNN: Invalid Number of Arguments');
end
% choose the activation function
if strcmp(activationFn, 'tanh')
aF = @tanh;
else % the default is sigmoid for now
aF = @sigmoid;
end
% Number of examples
m = size(X, 1);
% hypothesis values of 1st layer
h = aF([ones(m, 1) X] * Theta{1}');
% hypothesis values of the consecutive layers
for ii=2:numel(Theta)
h = aF([ones(m, 1) h] * Theta{ii}');
end
% prediction is the highest probability value
[~, p] = max(h, [], 2);
end