Showing posts with label coursera. Show all posts
Showing posts with label coursera. Show all posts

Monday, August 10, 2015

R Programming - Matrix Inversion Cache. Solution

My submission:
makeCacheMatrix <- function(x = matrix()) {
        inverse <- NULL
 
        setMatrix <- function(matrix = matrix()){
                x <<- matrix
        }
 
        getMatrix <- function() x
 
        setInverse <- function(inverseMatrix = matrix()){ 
                inverse <<- inverseMatrix
        } 
        getInverse <- function() inverse
        list(get = getMatrix, set = setMatrix, getI = getInverse, setI = setInverse)
}
 
 
## checks if the given makeCacheMatrix object already has it's inverse calculate.
## If not, it calculates it's inverse and caches it
 
cacheSolve <- function(x, ...) {
        ## Return a matrix that is the inverse of 'x' 
 
        if(is.null(x$getI())){
                print("Not cached. Recomputing...") 
                x$setI(solve(x$get()))
        }else {print("Found in cache")}
 
        x$getI()
}

Sunday, August 9, 2015

R Programming Week 3 Solutions

My solutions to week 3 exercises

1. Finding the best hospital in a state (best.R)

best <- function(state, outcome){
        data <- read.csv("outcome-of-care-measures.csv", colClasses = "character")
        data[, 11] <- as.numeric(data[, 11])
 
        possible <- c("heart attack", "heart failure", "pneumonia")
        if(!(state %in% data[["State"]])){
                stop("invalid state")
        }else if(!(outcome %in% possible)){
                stop("invalid outcome")
        }else{
                dataState <- data[data[["State"]]==state, ]
 
                #print(head(dataState$State, 10))
 
                diseaseCol <- 0
                if(outcome=="heart attack"){
                        diseaseCol <- 11
                }else if(outcome == "heart failure"){
                        diseaseCol <- 17
                }else diseaseCol <- 23
 
                hospitalNamesCol <- 2
 
                for(i in 1:nrow(dataState)){  
                        if(dataState[i, diseaseCol]=="Not Available"){
                                dataState[i, diseaseCol] <- NA
                        }
                }
 
                dataState <- dataState[!is.na(dataState[, diseaseCol]), ]
 
 
                #print(cbind(dataState$State, dataState[,2], dataState[,diseaseCol]))
 
                min <- 100000
                minState <- "z";
                #print(c("No of rows in dataState = ", nrow(dataState)))
                dataState[, diseaseCol] <- as.numeric(dataState[, diseaseCol])
                for(i in 1:nrow(dataState)){
                        #print(c("checking row", i))
                        #print(c("comparing ", dataState[i, diseaseCol], " against ", min))
                        if(dataState[i, diseaseCol]<min){
                                min <- dataState[i, diseaseCol] 
                                minState <- dataState[i, hospitalNamesCol]; 
                        }else if(dataState[i, diseaseCol]==min){
                                if(dataState[i, hospitalNamesCol]<minState){
                                        minState <- dataState[i, hospitalNamesCol];
                                }
                        }
                }
                minState
        }
}

2. Ranking hospitals by outcome in a state (rankhospital.R)

rankhospital <- function(state, outcome, num = "best"){
        data <- read.csv("outcome-of-care-measures.csv", colClasses = "character")
 
        possible <- c("heart attack", "heart failure", "pneumonia")
        if(!(state %in% data[["State"]])){
                stop("invalid state")
        }else if(!(outcome %in% possible)){
                stop("invalid outcome")
        }else{
                dataState <- data[data[["State"]]==state, ] 
 
                diseaseCol <- 0
                if(outcome=="heart attack"){
                        diseaseCol <- 11
                }else if(outcome == "heart failure"){
                        diseaseCol <- 17
                }else diseaseCol <- 23
 
                hospitalNamesCol <- 2
 
                for(i in 1:nrow(dataState)){  
                        if(dataState[i, diseaseCol]=="Not Available"){ 
                                dataState[i, diseaseCol] <- NA 
                        }
                } 
                # print(cbind(dataState[,2], dataState[,diseaseCol]))
 
                if(is.numeric(num) && nrow(dataState)<num)NA
                else{  
                        #remove "NA"s manually or use na.last=NA argument of order function
                        # dataState <- dataState[!is.na(dataState[, diseaseCol]), ]
 
                        # print(cbind(dataState[,2], dataState[,diseaseCol]))
 
                        dataState[, diseaseCol] <- as.numeric(dataState[, diseaseCol])
                        dataState <- dataState[order(dataState[, diseaseCol], dataState[, hospitalNamesCol], na.last = NA), ]
                        # print(cbind(dataState[,2], dataState[,diseaseCol]))
 
                        if(num=="best")dataState[1, 2]
                        else if(num=="worst")dataState[nrow(dataState), 2]
                        else dataState[num, 2] 
                }
        } 
}

3. Ranking hospitals in all states (rankall.R)

rankall <- function(outcome, num = "best"){
        data <- read.csv("outcome-of-care-measures.csv", colClasses = "character") 
 
        possible <- c("heart attack", "heart failure", "pneumonia") 
        if(!(outcome %in% possible)){
                stop("invalid outcome")
        }else{
 
 
                diseaseCol <- 0
                if(outcome=="heart attack"){
                        diseaseCol <- 11
                }else if(outcome == "heart failure"){
                        diseaseCol <- 17
                }else diseaseCol <- 23
 
                hospitalNamesCol <- 2
 
                for(i in 1:nrow(data)){  
                        if(data[i, diseaseCol]=="Not Available"){ 
                                data[i, diseaseCol] <- NA 
                        }
                }  
                r <-  split(data, data$State)  
                hNames <- vector()
                sNames <- vector()
                for(i in 1:length(r)){ 
                        nas <- sum(is.na(r[[i]][,diseaseCol]))
                        if(is.numeric(num) && num>(length(r[[i]][,2])-nas)){
                                hNames <- c(hNames, NA) 
                                sNames <- c(sNames, r[[i]][1, 7])
                                next
                        }
                        r[[i]][,diseaseCol] <- as.numeric(r[[i]][,diseaseCol])
 
                        r[[i]][,] <- r[[i]][order(r[[i]][, diseaseCol], r[[i]][, hospitalNamesCol]), ] 
  
                        if(num=="best")hNames <- c(hNames, r[[i]][1, 2])
                        else if(num=="worst")hNames <- c(hNames, r[[i]][length(r[[i]][,2])-nas, 2])
                        else hNames <- c(hNames, r[[i]][num, 2])
 
                        sNames <- c(sNames, r[[i]][1, 7])
                }
                dataframe <- data.frame(hospital = hNames, state = sNames)
        }
        dataframe 
}

Saturday, June 20, 2015

Dimensionality Reduction - K-Means Clustering and PCA - Machine Learning

My solutions to week 8 exercises :


Part 1 : Find Closest Centroids

function idx = findClosestCentroids(X, centroids)
%FINDCLOSESTCENTROIDS computes the centroid memberships for every example
%   idx = FINDCLOSESTCENTROIDS (X, centroids) returns the closest centroids
%   in idx for a dataset X where each row is a single example. idx = m x 1 
%   vector of centroid assignments (i.e. each entry in range [1..K])
%

% Set K
K = size(centroids, 1);

% You need to return the following variables correctly.
idx = zeros(size(X,1), 1);

% ====================== YOUR CODE HERE ======================
% Instructions: Go over every example, find its closest centroid, and store
%               the index inside idx at the appropriate location.
%               Concretely, idx(i) should contain the index of the centroid
%               closest to example i. Hence, it should be a value in the 
%               range 1..K
%
% Note: You can use a for-loop over the examples to compute this.
%
for i=1:size(X,1)
 minDistance = 100000000000;
 minIndex = -1;
 for j=1:K 
   vec = ones(size(centroids, 1)) * X(i);
   
   thisDistance = sum((X(i,:)-centroids(j, :)).^2);
   if thisDistance<minDistance minDistance = thisDistance; minIndex = j; end
 end
 idx(i) = minIndex;
end

% =============================================================

end



Part 2 : Compute Centroid Means

function centroids = computeCentroids(X, idx, K)
%COMPUTECENTROIDS returs the new centroids by computing the means of the 
%data points assigned to each centroid.
%   centroids = COMPUTECENTROIDS(X, idx, K) returns the new centroids by 
%   computing the means of the data points assigned to each centroid. It is
%   given a dataset X where each row is a single data point, a vector
%   idx of centroid assignments (i.e. each entry in range [1..K]) for each
%   example, and K, the number of centroids. You should return a matrix
%   centroids, where each row of centroids is the mean of the data points
%   assigned to it.
%

% Useful variables
[m n] = size(X);

% You need to return the following variables correctly.
centroids = zeros(K, n);


% ====================== YOUR CODE HERE ======================
% Instructions: Go over every centroid and compute mean of all points that
%               belong to it. Concretely, the row vector centroids(i, :)
%               should contain the mean of the data points assigned to
%               centroid i.
%
% Note: You can use a for-loop over the centroids to compute this.
%

for i = 1:K
 add=zeros(1, n);
 count=0;
 for j=1:m 
  if idx(j)==i 
  add = add+X(j,:); 
  count = count+1; 
  end
 end
 centroids(i, :) = add/count;
end

% =============================================================

end



Part 3 : PCA

function [U, S] = pca(X)
%PCA Run principal component analysis on the dataset X
%   [U, S, X] = pca(X) computes eigenvectors of the covariance matrix of X
%   Returns the eigenvectors U, the eigenvalues (on diagonal) in S
%

% Useful values
[m, n] = size(X);

% You need to return the following variables correctly.
U = zeros(n);
S = zeros(n);

% ====================== YOUR CODE HERE ======================
% Instructions: You should first compute the covariance matrix. Then, you
%               should use the "svd" function to compute the eigenvectors
%               and eigenvalues of the covariance matrix. 
%
% Note: When computing the covariance matrix, remember to divide by m (the
%       number of examples).
%

covarianceMatrixSigma = (X'*X)/m;
[U S V] = svd(covarianceMatrixSigma);

% =========================================================================

end



Part 4 : Project Data

function Z = projectData(X, U, K)
%PROJECTDATA Computes the reduced data representation when projecting only 
%on to the top k eigenvectors
%   Z = projectData(X, U, K) computes the projection of 
%   the normalized inputs X into the reduced dimensional space spanned by
%   the first K columns of U. It returns the projected examples in Z.
%

% You need to return the following variables correctly.
Z = zeros(size(X, 1), K);

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the projection of the data using only the top K 
%               eigenvectors in U (first K columns). 
%               For the i-th example X(i,:), the projection on to the k-th 
%               eigenvector is given as follows:
%                    x = X(i, :)';
%                    projection_k = x' * U(:, k);
%

Ureduced = U(:, 1:K);
Z = X*Ureduced; 

% =============================================================

end



Part 5 : Recover Data

function X_rec = recoverData(Z, U, K)
%RECOVERDATA Recovers an approximation of the original data when using the 
%projected data
%   X_rec = RECOVERDATA(Z, U, K) recovers an approximation the 
%   original data that has been reduced to K dimensions. It returns the
%   approximate reconstruction in X_rec.
%

% You need to return the following variables correctly.
X_rec = zeros(size(Z, 1), size(U, 1)); 
% ====================== YOUR CODE HERE ======================
% Instructions: Compute the approximation of the data by projecting back
%               onto the original space using the top K eigenvectors in U.
%
%               For the i-th example Z(i,:), the (approximate)
%               recovered data for dimension j is given as follows:
%                    v = Z(i, :)';
%                    recovered_j = v' * U(j, 1:K)';
%
%               Notice that U(j, 1:K) is a row vector.
%               

U_reducedT = U(:, 1:K)';
X_rec = Z*U_reducedT;  
% =============================================================

end

Friday, June 12, 2015

Neural Network Learning : Machine Learning

My solutions to Week 5 assignment questions.

Helpful links : https://github.com/jcgillespie/Coursera-Machine-Learning/tree/master/ex4

sigmoidGradient.m (#3):

function g = sigmoidGradient(z)
%SIGMOIDGRADIENT returns the gradient of the sigmoid function
%evaluated at z
%   g = SIGMOIDGRADIENT(z) computes the gradient of the sigmoid function
%   evaluated at z. This should work regardless if z is a matrix or a
%   vector. In particular, if z is a vector or matrix, you should return
%   the gradient for each element.

g = zeros(size(z));

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the gradient of the sigmoid function evaluated at
%               each value of z (z can be a matrix, vector or scalar).

sigmoidZ = zeros(size(z, 1), size(z, 2));
for i=1:size(sigmoidZ, 1)
 for j=1:size(sigmoidZ, 2)
  sigmoidZ(i,j) = sigmoid(z(i,j));
 end
end

oneMinus = 1-sigmoidZ;

for i=1:size(g,1)
 for j=1:size(g,2)
  g(i,j) = sigmoidZ(i,j)*oneMinus(i, j);
 end
end

% =============================================================

end




nnCostFunction(#1. #2. #4. #5):

function [J grad] = nnCostFunction(nn_params, ...
                                   input_layer_size, ...
                                   hidden_layer_size, ...
                                   num_labels, ...
                                   X, y, lambda)
%NNCOSTFUNCTION Implements the neural network cost function for a two layer
%neural network which performs classification
%   [J grad] = NNCOSTFUNCTON(nn_params, hidden_layer_size, num_labels, ...
%   X, y, lambda) computes the cost and gradient of the neural network. The
%   parameters for the neural network are "unrolled" into the vector
%   nn_params and need to be converted back into the weight matrices. 
% 
%   The returned parameter grad should be a "unrolled" vector of the
%   partial derivatives of the neural network.
%

% Reshape nn_params back into the parameters Theta1 and Theta2, the weight matrices
% for our 2 layer neural network
Theta1 = reshape(nn_params(1:hidden_layer_size * (input_layer_size + 1)), ...
                 hidden_layer_size, (input_layer_size + 1));

Theta2 = reshape(nn_params((1 + (hidden_layer_size * (input_layer_size + 1))):end), ...
                 num_labels, (hidden_layer_size + 1)); 
% Setup some useful variables
m = size(X, 1);
      
% You need to return the following variables correctly 
J = 0;
Theta1_grad = zeros(size(Theta1));
Theta2_grad = zeros(size(Theta2));

% ====================== YOUR CODE HERE ======================
% Instructions: You should complete the code by working through the
%               following parts.
%
% Part 1: Feedforward the neural network and return the cost in the
%         variable J. After implementing Part 1, you can verify that your
%         cost function computation is correct by verifying the cost
%         computed in ex4.m
%
% Part 2: Implement the backpropagation algorithm to compute the gradients
%         Theta1_grad and Theta2_grad. You should return the partial derivatives of
%         the cost function with respect to Theta1 and Theta2 in Theta1_grad and
%         Theta2_grad, respectively. After implementing Part 2, you can check
%         that your implementation is correct by running checkNNGradients
%
%         Note: The vector y passed into the function is a vector of labels
%               containing values from 1..K. You need to map this vector into a 
%               binary vector of 1's and 0's to be used with the neural network
%               cost function.
%
%         Hint: We recommend implementing backpropagation using a for-loop
%               over the training examples if you are implementing it for the 
%               first time.
%
% Part 3: Implement regularization with the cost function and gradients.
%
%         Hint: You can implement this around the code for
%               backpropagation. That is, you can compute the gradients for
%               the regularization separately and then add them to Theta1_grad
%               and Theta2_grad from Part 2.
%




% Ex1 
X = [ones(m, 1) X];
Y = zeros(size(y, 1), num_labels);

for i=1:size(Y, 1) Y(i, y(i)) = 1; end

a2 = zeros(hidden_layer_size, m+1);
a3 = zeros(num_labels, hidden_layer_size+1);
 

a2 = (Theta1*X');
z2 = a2;
a2 = sigmoid(a2); 

a2 = a2';
a2WithoutOnes = a2;
a2 = [ones(size(a2, 1), 1) a2]; 
a3 = a2*Theta2'; 
a3 = sigmoid(a3); 

predictions = a3;
logPredictions = log(predictions); 
 
tempLeftProd = zeros(size(a3, 1), 1);
tempRightProd = zeros(size(a3, 1), 1);

oneMinusY = 1-Y;
oneMinusPredictions = 1-predictions;

for i=1:size(a3, 1)
 tempLeftProd(i) = logPredictions(i,:)*Y(i,:)';
 tempRightProd(i) = log(oneMinusPredictions(i,:))*(oneMinusY(i,:)');
end

brackets = tempLeftProd+tempRightProd;
sumAllExamples = sum(brackets);
J = (-1/m)*sumAllExamples;





% Ex2
regularizationAdd = 0;
regAddLeft = zeros(hidden_layer_size, 1);

for i=1:hidden_layer_size
 for j=1:size(Theta1, 2)-1
  regAddLeft(i) = regAddLeft(i) + Theta1(i, j+1)^2;
 end
end

regAddRight = zeros(num_labels, 1);
for i=1:num_labels
 for j=1:size(Theta2, 2)-1 
  regAddRight(i) = regAddRight(i) + Theta2(i, j+1)^2;
 end
end

regularizationAdd = (lambda*(sum(regAddLeft)+sum(regAddRight)))/(2*m);
J = J+regularizationAdd; 






% Ex4
Delta1=0;
Delta2=0;

Theta1WithoutBias = Theta1(:, 2:end);
Theta2WithoutBias = Theta2(:, 2:end);

for t=1:m
 a1 = X(t, :)';
 z2 = Theta1*a1;
 a2 = [1; sigmoid(z2)];
 z3 = Theta2*a2;
 a3 = [sigmoid(z3)];
 
 d3 = a3-Y(t, :)'; 
 
 d2 = Theta2WithoutBias'*d3 .* sigmoidGradient(z2);
 %d2 = d2(2:end); % No need to do that. Theta2WithoutBias 
      % and z2(we add bias to a2, not z2) have 
      % already taken care of that
 
 Delta2 = Delta2 + d3*a2';
 Delta1 = Delta1 + d2*a1';
end

Theta1_grad = Delta1/m;
Theta2_grad = Delta2/m;





% Ex5 - regularization
Theta1_grad(:, 2:end) = Theta1_grad(:, 2:end)+(lambda/m)*Theta1WithoutBias;
Theta2_grad(:, 2:end) = Theta2_grad(:, 2:end)+(lambda/m)*Theta2WithoutBias;
% -------------------------------------------------------------

% =========================================================================

% Unroll gradients
grad = [Theta1_grad(:) ; Theta2_grad(:)]; 

end


Monday, June 8, 2015

Neural Networks : Representation : Machine Learning : Week 4

My solutions to Week 4 assignments:

Part 1: Regularied Logistic Regression

function [J, grad] = lrCostFunction(theta, X, y, lambda)
%LRCOSTFUNCTION Compute cost and gradient for logistic regression with 
%regularization
%   J = LRCOSTFUNCTION(theta, X, y, lambda) computes the cost of using
%   theta as the parameter for regularized logistic regression and the
%   gradient of the cost w.r.t. to the parameters. 

% Initialize some useful values
m = length(y); % number of training examples

% You need to return the following variables correctly 
J = 0;
grad = zeros(size(theta));

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost of a particular choice of theta.
%               You should set J to the cost.
%               Compute the partial derivatives and set grad to the partial
%               derivatives of the cost w.r.t. each parameter in theta
%
% Hint: The computation of the cost function and gradients can be
%       efficiently vectorized. For example, consider the computation
%
%           sigmoid(X * theta)
%
%       Each row of the resulting matrix will contain the value of the
%       prediction for that example. You can make use of this to vectorize
%       the cost function and gradient computations. 
%
% Hint: When computing the gradient of the regularized cost function, 
%       there're many possible vectorized solutions, but one solution
%       looks like:
%           grad = (unregularized gradient for logistic regression)
%           temp = theta; 
%           temp(1) = 0;   % because we don't add anything for j = 0  
%           grad = grad + YOUR_CODE_HERE (using the temp variable)
% 

thetaTx = (theta'*X')';
h = sigmoid(thetaTx);  
leftJ = -(1/m)*(sum(y'*log(h)+(1-y)'*log(1-h)));
 
rightJ = (lambda/(2*m))*sum((theta.^2)(2:end,1));
 
J = leftJ+rightJ;

error = h-y; 
grad = ((error'*X)' + (lambda*theta))/m;
grad(1) = (error'*X(:,1))/m ; 

% =============================================================

grad = grad(:);

end

Part 2: One-vs-all classifier training

function [all_theta] = oneVsAll(X, y, num_labels, lambda)
%ONEVSALL trains multiple logistic regression classifiers and returns all
%the classifiers in a matrix all_theta, where the i-th row of all_theta 
%corresponds to the classifier for label i
%   [all_theta] = ONEVSALL(X, y, num_labels, lambda) trains num_labels
%   logisitc regression classifiers and returns each of these classifiers
%   in a matrix all_theta, where the i-th row of all_theta corresponds 
%   to the classifier for label i

% Some useful variables
m = size(X, 1);
n = size(X, 2);

% You need to return the following variables correctly 
all_theta = zeros(num_labels, n + 1);

% Add ones to the X data matrix
X = [ones(m, 1) X];

% ====================== YOUR CODE HERE ======================
% Instructions: You should complete the following code to train num_labels
%               logistic regression classifiers with regularization
%               parameter lambda. 
%
% Hint: theta(:) will return a column vector.
%
% Hint: You can use y == c to obtain a vector of 1's and 0's that tell use 
%       whether the ground truth is true/false for this class.
%
% Note: For this assignment, we recommend using fmincg to optimize the cost
%       function. It is okay to use a for-loop (for c = 1:num_labels) to
%       loop over the different classes.
%
%       fmincg works similarly to fminunc, but is more efficient when we
%       are dealing with large number of parameters.
%
% Example Code for fmincg:
%
%     % Set Initial theta
%     initial_theta = zeros(n + 1, 1);
%     
%     % Set options for fminunc
%     options = optimset('GradObj', 'on', 'MaxIter', 50);
% 
%     % Run fmincg to obtain the optimal theta
%     % This function will return theta and the cost 
%     [theta] = ...
%         fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), ...
%                 initial_theta, options);
%


options = optimset('GradObj', 'on', 'MaxIter', 50);

for c = 1:num_labels
 initial_theta = zeros(n+1, 1);
 [theta] = fmincg(@(t)(lrCostFunction(t, X, (y==c), lambda)), initial_theta, options);
 all_theta(c,:) = theta;
end


% =========================================================================


end

Part 3: One-vs-all classifier prediction

function p = predictOneVsAll(all_theta, X)
%PREDICT Predict the label for a trained one-vs-all classifier. The labels 
%are in the range 1..K, where K = size(all_theta, 1). 
%  p = PREDICTONEVSALL(all_theta, X) will return a vector of predictions
%  for each example in the matrix X. Note that X contains the examples in
%  rows. all_theta is a matrix where the i-th row is a trained logistic
%  regression theta vector for the i-th class. You should set p to a vector
%  of values from 1..K (e.g., p = [1; 3; 1; 2] predicts classes 1, 3, 1, 2
%  for 4 examples) 

m = size(X, 1);
num_labels = size(all_theta, 1);

% You need to return the following variables correctly 
p = zeros(size(X, 1), 1);

% Add ones to the X data matrix
X = [ones(m, 1) X];

% ====================== YOUR CODE HERE ======================
% Instructions: Complete the following code to make predictions using
%               your learned logistic regression parameters (one-vs-all).
%               You should set p to a vector of predictions (from 1 to
%               num_labels).
%
% Hint: This code can be done all vectorized using the max function.
%       In particular, the max function can also return the index of the 
%       max element, for more information see 'help max'. If your examples 
%       are in rows, then, you can use max(A, [], 2) to obtain the max 
%       for each row.
%       
  
z = X*all_theta';

for i = 1:size(z, 1)
 for j=1:size(z, 2)
  z(i, j) = pinv(1+pinv(e^z(i, j)));
 end
end

pSigmoid = z;

[maxProbabilities indices] = max(pSigmoid, [], 2);
p = indices;

% =========================================================================

end

Part 4: Neural Network Prediction Function

function p = predict(Theta1, Theta2, X)
%PREDICT Predict the label of an input given a trained neural network
%   p = PREDICT(Theta1, Theta2, X) outputs the predicted label of X given the
%   trained weights of a neural network (Theta1, Theta2)

% Useful values
m = size(X, 1);
num_labels = size(Theta2, 1);

% You need to return the following variables correctly 
p = zeros(size(X, 1), 1);

% ====================== YOUR CODE HERE ======================
% Instructions: Complete the following code to make predictions using
%               your learned neural network. You should set p to a 
%               vector containing labels between 1 to num_labels.
%
% Hint: The max function might come in useful. In particular, the max
%       function can also return the index of the max element, for more
%       information see 'help max'. If your examples are in rows, then, you
%       can use max(A, [], 2) to obtain the max for each row.
%

X = [ones(m, 1) X];
z = X*Theta1';

for i = 1:size(z, 1)
 for j=1:size(z, 2)
  z(i, j) = pinv(1+pinv(e^z(i, j)));
 end
end

pSigmoid = z; 
pSigmoid = [ones(size(pSigmoid, 1), 1) pSigmoid];

z1 = pSigmoid*Theta2';
[maxProbabilities indices] = max(z1, [], 2);
p = indices; 

% =========================================================================


end