<h2>Introduction</h2>
<p>a. <em>A robot may not injure a human being or, through inaction, allow a human being to come to harm.<br>
b. A robot must obey orders given it by human beings except where such orders would conflict with the First Law.<br>
c. A robot must protect its own existence as long as such protection does not conflict with the First or Second Law.</em></p>
<pre><code>      Isaac Asimov's Three Laws of Robotics </code></pre>
<p><em>Any sufficiently advanced technology is indistinguishable from magic.</em></p>
<pre><code>      Arthur C Clarke.   </code></pre>
<div>
<p>In this 5th part on Deep Learning from first Principles in Python, R and Octave, I solve the MNIST data set of handwritten digits (shown below), from the basics. To do this, I construct a L-Layer, vectorized Deep Learning implementation in Python, R and Octave from scratch and classify the  MNIST data set. The MNIST training data set  contains 60000 handwritten digits from 0-9, and a test set of 10000 digits. MNIST, is a popular dataset for running Deep Learning tests, and has been rightfully termed as the ‘drosophila’ of Deep Learning, by none other than the venerable Prof Geoffrey Hinton.</p>
<p><img data-orig-file="https://gigadom.files.wordpress.com/2018/03/mnist1.jpeg?w=456" data-orig-size="584,387" data-medium-file="https://gigadom.files.wordpress.com/2018/03/mnist1.jpeg?w=456?w=300" data-attachment-id="6460" data-image-meta="{" data-image-description="" src="https://gigadom.files.wordpress.com/2018/03/mnist1.jpeg?w=456" data-permalink="https://gigadom.wordpress.com/2018/03/23/deep-learning-from-first-principles-in-python-r-and-octave-part-5/mnist-2/" data-large-file="https://gigadom.files.wordpress.com/2018/03/mnist1.jpeg?w=456?w=584" alt="" data-image-title="mnist" sizes="(max-width: 584px) 100vw, 584px" data-comments-opened="1" class="wp-image-6460" data-recalc-dims="1"></p>
<p>The ‘Deep Learning from first principles in Python, R and Octave’ series, so far included  <a rel="nofollow" href="https://gigadom.wordpress.com/2018/01/04/deep-learning-from-basic-principles-in-python-r-and-octave-part-1/" target="_blank">Part 1 </a>, where I had implemented logistic regression as a simple Neural Network. <a rel="nofollow" href="https://gigadom.wordpress.com/2018/01/11/deep-learning-from-first-principles-in-python-r-and-octave-part-2/" target="_blank">Part 2</a> implemented the most elementary neural network with 1 hidden layer, but  with any number of activation units in that layer, and a sigmoid activation at the output layer.</p>
<p>This post, ‘Deep Learning from first principles in Python, R and Octave – Part 5’ largely builds upon <a rel="nofollow" href="https://gigadom.wordpress.com/2018/01/30/deep-learning-from-first-principles-in-python-r-and-octave-part-3/" target="_blank">Part3</a>. in which I implemented a multi-layer Deep Learning network, with an arbitrary number of hidden layers and activation units per hidden layer and with the output layer was based on the sigmoid unit, for binary classification. In <a rel="nofollow" href="https://gigadom.wordpress.com/2018/02/26/deep-learning-from-first-principles-in-python-r-and-octave-part-4/" target="_blank">Part 4,</a> I derive the Jacobian of a Softmax, the Cross entropy loss and the gradient equations for a multi-class Softmax classifier. I also  implement a simple Neural Network using Softmax classifications in Python, R and Octave.</p>
<p>In this post I combine <a rel="nofollow" href="https://gigadom.wordpress.com/2018/01/30/deep-learning-from-first-principles-in-python-r-and-octave-part-3/" target="_blank">Part 3</a> and <a rel="nofollow" href="https://gigadom.wordpress.com/2018/02/26/deep-learning-from-first-principles-in-python-r-and-octave-part-4/" target="_blank">Part 4</a> to to build a L-layer Deep Learning network, with arbitrary number of hidden layers and hidden units, which can do both binary (sigmoid) and multi-class (softmax) classification.</p>
<p>The generic, vectorized L-Layer Deep Learning Network implementations in Python, R and Octave can be cloned/downloaded from GitHub at <a rel="nofollow" href="https://github.com/tvganesh/DeepLearning-Part5" target="_blank">DeepLearning-Part5</a>. This implementation allows for arbitrary number of hidden layers and hidden layer units. The activation function at the hidden layers can be one of sigmoid, relu and tanh (will be adding leaky relu soon). The output activation can be used for binary classification with the ‘sigmoid’, or multi-class classification with ‘softmax’. Feel free to download and play around with the code!</p>
<p>I thought the exercise of combining the two parts(Part 3, &amp; Part 4)  would be a breeze. But it was anything but. Incorporating a Softmax classifier into the generic L-Layer Deep Learning model was a challenge. Moreover I found that I could not use the gradient descent on 60,000 training samples as my laptop ran out of memory. So I had to implement Stochastic Gradient Descent (SGD) for Python, R and Octave. In addition, I had to also implement the numerically stable version of Softmax, as the softmax and its derivative would result in NaNs.</p>
<h3>Numerically stable Softmax</h3>
<p>The Softmax function <img alt="S_{j} =frac{e^{Z_{j}}}{sum_{i}^{k}e^{Z_{i}}}" title="S_{j} =frac{e^{Z_{j}}}{sum_{i}^{k}e^{Z_{i}}}" src="https://s0.wp.com/latex.php?latex=S_%7Bj%7D+%3D%5Cfrac%7Be%5E%7BZ_%7Bj%7D%7D%7D%7B%5Csum_%7Bi%7D%5E%7Bk%7De%5E%7BZ_%7Bi%7D%7D%7D&bg=ffffff&%23038;fg=444444&%23038;s=0" class="latex"> can be numerically unstable because of the division of large exponentials.  To handle this problem we have to implement stable Softmax function as below</p>
<p><img alt="S_{j} =frac{e^{Z_{j}}}{sum_{i}^{k}e^{Z_{i}}}" title="S_{j} =frac{e^{Z_{j}}}{sum_{i}^{k}e^{Z_{i}}}" src="https://s0.wp.com/latex.php?latex=S_%7Bj%7D+%3D%5Cfrac%7Be%5E%7BZ_%7Bj%7D%7D%7D%7B%5Csum_%7Bi%7D%5E%7Bk%7De%5E%7BZ_%7Bi%7D%7D%7D&bg=ffffff&%23038;fg=444444&%23038;s=0" class="latex"><br>
<img alt="S_{j} =frac{e^{Z_{j}}}{sum_{i}^{k}e^{Z_{i}}} = frac{Ce^{Z_{j}}}{Csum_{i}^{k}e^{Z_{i}}} = frac{e^{Z_{j}+log(C)}}{sum_{i}^{k}e^{Z_{i}+log(C)}}" title="S_{j} =frac{e^{Z_{j}}}{sum_{i}^{k}e^{Z_{i}}} = frac{Ce^{Z_{j}}}{Csum_{i}^{k}e^{Z_{i}}} = frac{e^{Z_{j}+log(C)}}{sum_{i}^{k}e^{Z_{i}+log(C)}}" src="https://s0.wp.com/latex.php?latex=S_%7Bj%7D+%3D%5Cfrac%7Be%5E%7BZ_%7Bj%7D%7D%7D%7B%5Csum_%7Bi%7D%5E%7Bk%7De%5E%7BZ_%7Bi%7D%7D%7D+%3D+%5Cfrac%7BCe%5E%7BZ_%7Bj%7D%7D%7D%7BC%5Csum_%7Bi%7D%5E%7Bk%7De%5E%7BZ_%7Bi%7D%7D%7D+%3D+%5Cfrac%7Be%5E%7BZ_%7Bj%7D%2Blog%28C%29%7D%7D%7B%5Csum_%7Bi%7D%5E%7Bk%7De%5E%7BZ_%7Bi%7D%2Blog%28C%29%7D%7D&bg=ffffff&%23038;fg=444444&%23038;s=0" class="latex"><br>
Therefore <img alt="S_{j}  = frac{e^{Z_{j}+ D}}{sum_{i}^{k}e^{Z_{i}+ D}}" title="S_{j}  = frac{e^{Z_{j}+ D}}{sum_{i}^{k}e^{Z_{i}+ D}}" src="https://s0.wp.com/latex.php?latex=S_%7Bj%7D%C2%A0+%3D+%5Cfrac%7Be%5E%7BZ_%7Bj%7D%2B+D%7D%7D%7B%5Csum_%7Bi%7D%5E%7Bk%7De%5E%7BZ_%7Bi%7D%2B+D%7D%7D&bg=ffffff&%23038;fg=444444&%23038;s=0" class="latex"><br>
Here ‘D’ can be anything. A common choice is<br>
<img alt="D=-max(Z_{1},Z_{2},... Z_{k})" title="D=-max(Z_{1},Z_{2},... Z_{k})" src="https://s0.wp.com/latex.php?latex=D%3D-max%28Z_%7B1%7D%2CZ_%7B2%7D%2C...+Z_%7Bk%7D%29&bg=ffffff&%23038;fg=444444&%23038;s=0" class="latex"></p>
<p>Here is the stable Softmax implementation in Python</p>
<pre><code># A numerically stable Softmax implementation
def stableSoftmax(Z):  
    #Compute the softmax of vector x in a numerically stable way.
    shiftZ = Z.T - np.max(Z.T,axis=1).reshape(-1,1)
    exp_scores = np.exp(shiftZ)
    # normalize them for each example
    A = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) 
    cache=Z
    return A,cache
</code></pre>
<p>While trying to create a L-Layer generic Deep Learning network in the 3 languages, I found it useful to ensure that the model executed correctly on smaller datasets.  You can run into numerous problems while setting up the matrices, which becomes extremely difficult to debug. So in this post, I run the model on 2 smaller data for sets used in my earlier posts(Part 3 &amp; Part4) , in each of the languages, before running the generic model on MNIST.</p>
<p>Here is a fair warning. if you think you can dive directly into Deep Learning, with just some basic knowledge of Machine Learning, you are bound to run into serious issues. Moreover, your knowledge will be incomplete. It is essential that you have a good grasp of Machine and Statistical Learning, the different algorithms, the measures and metrics for selecting the models etc.It would help to be conversant with all the ML models, ML concepts, validation techniques, classification measures  etc. Check out the internet/books for background.</p>
<p>Incidentally you could also check out my book, <a rel="nofollow" href="https://gigadom.wordpress.com/2017/12/05/my-book-practical-machine-learning-with-r-and-python-on-amazon/" target="_blank">Practical Machine Learning in R and Python – Machine Learning in Stereo</a>, available on Amazon. In this book, I implement different ML algorithms,  regularization techniques, model selection, ensemble methods, key measures and metrics. My book is compact, minimalist  and includes implementations of many ML algorithms in R and Python, and can be used as a handy reference.</p>
<p><img data-orig-file="https://gigadom.files.wordpress.com/2018/03/untitled1.png?w=450&amp;h=214&amp;fit=676%2C214" data-orig-size="676,214" data-medium-file="https://gigadom.files.wordpress.com/2018/03/untitled1.png?w=450&amp;h=214&amp;fit=676%2C214?w=300" data-attachment-id="6461" data-image-meta="{" data-image-description="" src="https://gigadom.files.wordpress.com/2018/03/untitled1.png?w=450&h=214&fit=676%2C214" data-permalink="https://gigadom.wordpress.com/2018/03/23/deep-learning-from-first-principles-in-python-r-and-octave-part-5/untitled1-8/" data-large-file="https://gigadom.files.wordpress.com/2018/03/untitled1.png?w=450&amp;h=214&amp;fit=676%2C214?w=676" alt="" data-image-title="untitled1" sizes="(max-width: 676px) 100vw, 676px" data-comments-opened="1" class="wp-image-6461" data-recalc-dims="1"></p>
</div>
<div>
<h3>1. Random dataset with Sigmoid activation – Python</h3>
<p>This random data with 9 clusters, was used in my post <a rel="nofollow" href="https://gigadom.wordpress.com/2018/01/30/deep-learning-from-first-principles-in-python-r-and-octave-part-3/" target="_blank">Deep Learning from first principles in Python, R and Octave – Part 3</a> , and was used to test the complete L-layer Deep Learning network with Sigmoid activation.</p>
<pre><code><span>import</span> numpy <span>as</span> np
<span>import</span> matplotlib
<span>import</span> matplotlib.pyplot <span>as</span> plt
<span>import</span> pandas <span>as</span> pd
<span>from</span> sklearn.datasets <span>import</span> make_classification, make_blobs
<span>exec</span>(open(<span>&quot;DLfunctions51.py&quot;</span>).read()) # Cannot import in Rmd.
# Create a random data set with 9 centeres
X1, Y1 = make_blobs(n_samples = <span>400</span>, n_features = <span>2</span>, centers = <span>9</span>,cluster_std = <span>1.3</span>, random_state =<span>4</span>)
                       
<span>#Create 2 classes</span>
Y1=Y1.reshape(<span>400</span>,<span>1</span>)
Y1 = Y1 % <span>2</span>
X2=X1.T
Y2=Y1.T
# Set the dimensions of L -layer DL network
layersDimensions = [<span>2</span>, <span>9</span>, <span>9</span>,<span>1</span>] <span># 4-layer model</span>
# Execute DL network with hidden activation=relu and sigmoid output function
parameters = L_Layer_DeepModel(X2, Y2, layersDimensions, hiddenActivationFunc=<span>'relu'</span>, outputActivationFunc=<span>&quot;sigmoid&quot;</span>,learningRate = <span>0.3</span>,num_iterations = <span>2500</span>, print_cost = <span>True</span>)</code></pre>
</div>
<div>
<h1><img data-orig-file="https://gigadom.files.wordpress.com/2018/03/fig11.png?w=456" data-orig-size="389,278" data-medium-file="https://gigadom.files.wordpress.com/2018/03/fig11.png?w=456?w=300" data-attachment-id="6443" data-image-meta="{" data-image-description="" src="https://gigadom.files.wordpress.com/2018/03/fig11.png?w=456" data-permalink="https://gigadom.wordpress.com/2018/03/23/deep-learning-from-first-principles-in-python-r-and-octave-part-5/fig11/" data-large-file="https://gigadom.files.wordpress.com/2018/03/fig11.png?w=456?w=389" alt="" data-image-title="fig11" sizes="(max-width: 389px) 100vw, 389px" data-comments-opened="1" class="wp-image-6443" data-recalc-dims="1"></h1>
<h3>2. Spiral dataset with Softmax activation – Python</h3>
<p>The Spiral data was used in my post <a rel="nofollow" href="https://gigadom.wordpress.com/2018/02/26/deep-learning-from-first-principles-in-python-r-and-octave-part-4/" target="_blank">Deep Learning from first principles in Python, R and Octave – Part 4</a> and was used to test the complete L-layer Deep Learning network with multi-class Softmax activation at the output layer</p>
<pre><code><span>import</span> numpy <span>as</span> np
<span>import</span> matplotlib
<span>import</span> matplotlib.pyplot <span>as</span> plt
<span>import</span> pandas <span>as</span> pd
<span>from</span> sklearn.datasets <span>import</span> make_classification, make_blobs
<span>exec</span>(open(<span>&quot;DLfunctions51.py&quot;</span>).read())

<span># Create an input data set - Taken from CS231n Convolutional Neural networks</span>
<span># http://cs231n.github.io/neural-networks-case-study/</span>
N = <span>100</span> <span># number of points per class</span>
D = <span>2</span> <span># dimensionality</span>
K = <span>3</span> <span># number of classes</span>
X = np.zeros((N*K,D)) <span># data matrix (each row = single example)</span>
y = np.zeros(N*K, dtype=<span>'uint8'</span>) <span># class labels</span>
<span>for</span> j <span>in</span> range(K):
  ix = range(N*j,N*(j+<span>1</span>))
  r = np.linspace(<span>0.0</span>,<span>1</span>,N) <span># radius</span>
  t = np.linspace(j*<span>4</span>,(j+<span>1</span>)*<span>4</span>,N) + np.random.randn(N)*<span>0.2</span> <span># theta</span>
  X[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
  y[ix] = j

X1=X.T
Y1=y.reshape(-<span>1</span>,<span>1</span>).T
numHidden=<span>100</span> <span># No of hidden units in hidden layer</span>
numFeats= <span>2</span> <span># dimensionality</span>
numOutput = <span>3</span> <span># number of classes</span>
# Set the dimensions of the layers
layersDimensions=[numFeats,numHidden,numOutput]
parameters = L_Layer_DeepModel(X1, Y1, layersDimensions, hiddenActivationFunc=<span>'relu'</span>, outputActivationFunc=<span>&quot;softmax&quot;</span>,learningRate = <span>0.6</span>,num_iterations = <span>9000</span>, print_cost = <span>True</span>)</code></pre>
<pre><code>## Cost after iteration 0: 1.098759
## Cost after iteration 1000: 0.112666
## Cost after iteration 2000: 0.044351
## Cost after iteration 3000: 0.027491
## Cost after iteration 4000: 0.021898
## Cost after iteration 5000: 0.019181
## Cost after iteration 6000: 0.017832
## Cost after iteration 7000: 0.017452
## Cost after iteration 8000: 0.017161</code></pre>
</div>
<div>
<h1><img data-orig-file="https://gigadom.files.wordpress.com/2018/03/fig12.png?w=456" data-orig-size="389,278" data-medium-file="https://gigadom.files.wordpress.com/2018/03/fig12.png?w=456?w=300" data-attachment-id="6444" data-image-meta="{" data-image-description="" src="https://gigadom.files.wordpress.com/2018/03/fig12.png?w=456" data-permalink="https://gigadom.wordpress.com/2018/03/23/deep-learning-from-first-principles-in-python-r-and-octave-part-5/fig12/" data-large-file="https://gigadom.files.wordpress.com/2018/03/fig12.png?w=456?w=389" alt="" data-image-title="fig12" sizes="(max-width: 389px) 100vw, 389px" data-comments-opened="1" class="wp-image-6444" data-recalc-dims="1"></h1>
<h3>3. MNIST dataset with Softmax activation – Python</h3>
<p>In the code below, I execute Stochastic Gradient Descent on the MNIST training data of 60000. I used a mini-batch size of 1000. Python takes about 40 minutes to crunch the data. In addition I also compute the Confusion Matrix and other metrics like Accuracy, Precision and Recall for the MNIST data set. I get an accuracy of 0.93 on the MNIST test set. This accuracy can be improved by choosing more hidden layers or more hidden units and possibly also tweaking the learning rate and the number of epochs.</p>
<pre><code><span>import</span> numpy <span>as</span> np
<span>import</span> matplotlib
<span>import</span> matplotlib.pyplot <span>as</span> plt
<span>import</span> pandas <span>as</span> pd
<span>import</span> math
<span>from</span> sklearn.datasets <span>import</span> make_classification, make_blobs
<span>from</span> sklearn.metrics <span>import</span> confusion_matrix
<span>from</span> sklearn.metrics <span>import</span> accuracy_score, precision_score, recall_score, f1_score
<span>exec</span>(open(<span>&quot;DLfunctions51.py&quot;</span>).read())
<span>exec</span>(open(<span>&quot;load_mnist.py&quot;</span>).read())
# Read the MNIST training and test sets
training=list(read(dataset=<span>'training'</span>,path=<span>&quot;.\\mnist&quot;</span>))
test=list(read(dataset=<span>'testing'</span>,path=<span>&quot;.\\mnist&quot;</span>))
# Create labels and pixel arrays
lbls=[]
pxls=[]
<span>print</span>(len(training))
<span>#for i in range(len(training)):</span>
<span>for</span> i <span>in</span> range(<span>60000</span>):
       l,p=training[i]
       lbls.append(l)
       pxls.append(p)
labels= np.array(lbls)
pixels=np.array(pxls)       
y=labels.reshape(-<span>1</span>,<span>1</span>)
X=pixels.reshape(pixels.shape[<span>0</span>],-<span>1</span>)
X1=X.T
Y1=y.T
# Set the dimensions of the layers. The MNIST data is 28x28 pixels= 784
# Hence input layer is 784. For the 10 digits the Softmax classifier
# has to handle 10 outputs
layersDimensions=[<span>784</span>, <span>15</span>,<span>9</span>,<span>10</span>] <span># Works very well,lr=0.01,mini_batch =1000, total=20000</span>
np.random.seed(<span>1</span>)
costs = []  
# Run Stochastic Gradient Descent with Learning Rate=0.01, mini batch size=1000
# number of epochs=3000
parameters = L_Layer_DeepModel_SGD(X1, Y1, layersDimensions, hiddenActivationFunc=<span>'relu'</span>, outputActivationFunc=<span>&quot;softmax&quot;</span>,learningRate = <span>0.01</span> ,mini_batch_size =<span>1000</span>, num_epochs = <span>3000</span>, print_cost = <span>True</span>)

# Compute the Confusion Matrix on Training set
<span># Compute the training accuracy, precision and recall</span>
proba=predict_proba(parameters, X1,outputActivationFunc=<span>&quot;softmax&quot;</span>)
<span>#A2, cache = forwardPropagationDeep(X1, parameters)</span>
<span>#proba=np.argmax(A2, axis=0).reshape(-1,1)</span>
a=confusion_matrix(Y1.T,proba)
<span>print</span>(a)
<span>from</span> sklearn.metrics <span>import</span> accuracy_score, precision_score, recall_score, f1_score
<span>print</span>(<span>'Accuracy: {:.2f}'</span>.format(accuracy_score(Y1.T, proba)))
<span>print</span>(<span>'Precision: {:.2f}'</span>.format(precision_score(Y1.T, proba,average=<span>&quot;micro&quot;</span>)))
<span>print</span>(<span>'Recall: {:.2f}'</span>.format(recall_score(Y1.T, proba,average=<span>&quot;micro&quot;</span>)))

# Read the test data
lbls=[]
pxls=[]
<span>print</span>(len(test))
<span>for</span> i <span>in</span> range(<span>10000</span>):
       l,p=test[i]
       lbls.append(l)
       pxls.append(p)
testLabels= np.array(lbls)
testPixels=np.array(pxls)       
ytest=testLabels.reshape(-<span>1</span>,<span>1</span>)
Xtest=testPixels.reshape(testPixels.shape[<span>0</span>],-<span>1</span>)
X1test=Xtest.T
Y1test=ytest.T

# Compute the Confusion Matrix on Test set
<span># Compute the test accuracy, precision and recall</span>
probaTest=predict_proba(parameters, X1test,outputActivationFunc=<span>&quot;softmax&quot;</span>)
<span>#A2, cache = forwardPropagationDeep(X1, parameters)</span>
<span>#proba=np.argmax(A2, axis=0).reshape(-1,1)</span>
a=confusion_matrix(Y1test.T,probaTest)
<span>print</span>(a)
<span>from</span> sklearn.metrics <span>import</span> accuracy_score, precision_score, recall_score, f1_score
<span>print</span>(<span>'Accuracy: {:.2f}'</span>.format(accuracy_score(Y1test.T, probaTest)))
<span>print</span>(<span>'Precision: {:.2f}'</span>.format(precision_score(Y1test.T, probaTest,average=<span>&quot;micro&quot;</span>)))
<span>print</span>(<span>'Recall: {:.2f}'</span>.format(recall_score(Y1test.T, probaTest,average=<span>&quot;micro&quot;</span>)))
</code></pre>
<pre><code>##1.  Confusion Matrix of Training set
       0     1    2    3    4    5    6    7    8    9
## [[5854    0   19    2   10    7    0    1   24    6]
##  [   1 6659   30   10    5    3    0   14   20    0]
##  [  20   24 5805   18    6   11    2   32   37    3]
##  [   5    4  175 5783    1   27    1   58   60   17]
##  [   1   21    9    0 5780    0    5    2   12   12]
##  [  29    9   21  224    6 4824   18   17  245   28]
##  [   5    4   22    1   32   12 5799    0   43    0]
##  [   3   13  148  154   18    3    0 5883    4   39]
##  [  11   34   30   21   13   16    4    7 5703   12]
##  [  10    4    1   32  135   14    1   92  134 5526]]

##2. Accuracy, Precision, Recall of  Training set
## Accuracy: 0.96
## Precision: 0.96
## Recall: 0.96

##3. Confusion Matrix of Test set
       0     1    2    3    4    5    6    7    8    9
## [[ 954    1    8    0    3    3    2    4    4    1]
##  [   0 1107    6    5    0    0    1    2   14    0]
##  [  11    7  957   10    5    0    5   20   16    1]
##  [   2    3   37  925    3   13    0    8   18    1]
##  [   2    6    1    1  944    0    7    3    4   14]
##  [  12    5    4   45    2  740   24    8   42   10]
##  [   8    4    4    2   16    9  903    0   12    0]
##  [   4   10   27   18    5    1    0  940    1   22]
##  [  11   13    6   13    9   10    7    2  900    3]
##  [   8    5    1    7   50    7    0   20   29  882]]
##4. Accuracy, Precision, Recall of  Training set
## Accuracy: 0.93
## Precision: 0.93
## Recall: 0.93</code></pre>
</div>
<div>
<h1><img data-orig-file="https://gigadom.files.wordpress.com/2018/03/fig1.png?w=456" data-orig-size="570,455" data-medium-file="https://gigadom.files.wordpress.com/2018/03/fig1.png?w=456?w=300" data-attachment-id="6445" data-image-meta="{" data-image-description="" src="https://gigadom.files.wordpress.com/2018/03/fig1.png?w=456" data-permalink="https://gigadom.wordpress.com/2018/03/23/deep-learning-from-first-principles-in-python-r-and-octave-part-5/fig1-16/" data-large-file="https://gigadom.files.wordpress.com/2018/03/fig1.png?w=456?w=570" alt="" data-image-title="fig1" sizes="(max-width: 570px) 100vw, 570px" data-comments-opened="1" class="wp-image-6445" data-recalc-dims="1"></h1>
<h3>4. Random dataset with Sigmoid activation – R code</h3>
<p>This is the random data set used in the Python code above which was saved as a CSV. The code is used to test a L -Layer DL network with Sigmoid Activation in R.</p>
<pre><code><span><span>source</span><span>(</span><span>&quot;DLfunctions5.R&quot;</span><span>)
</span># Read the random data set
z</span> <span>&lt;-</span> <span>as.matrix</span><span>(</span><span>read.csv</span><span>(</span><span>&quot;data.csv&quot;</span>,<span>header</span><span>=</span><span>FALSE</span><span>)</span><span>)</span> 
<span>x</span> <span>&lt;-</span> <span>z</span><span>[</span>,<span>1</span><span>:</span><span>2</span><span>]</span>
<span>y</span> <span>&lt;-</span> <span>z</span><span>[</span>,<span>3</span><span>]</span>
<span>X</span> <span>&lt;-</span> <span>t</span><span>(</span><span>x</span><span>)</span>
<span>Y</span> <span>&lt;-</span> <span>t</span><span>(</span><span>y</span><span>)
</span># Set the dimensions of the  layer
<span>layersDimensions</span> <span>=</span> <span>c</span><span>(</span><span>2</span>, <span>9</span>, <span>9</span>,<span>1</span><span>)</span>

<span># Run Gradient Descent on the data set with relu hidden unit activation </span># sigmoid activation unit in the output layer
<span>retvals</span> <span>=</span> <span>L_Layer_DeepModel</span><span>(</span><span>X</span>, <span>Y</span>, <span>layersDimensions</span>,
                            <span>hiddenActivationFunc</span><span>=</span><span>'relu'</span>,
                            <span>outputActivationFunc</span><span>=</span><span>&quot;sigmoid&quot;</span>,
                            <span>learningRate</span> <span>=</span> <span>0.3</span>,
                            <span>numIterations</span> <span>=</span> <span>5000</span>, 
                            <span>print_cost</span> <span>=</span> <span>True</span><span>)
#Plot the cost vs iterations
iterations &lt;-seq(0,5000,1000)
costs=retvals$costs
df=data.frame(iterations,costs)
ggplot(df,aes(x=iterations,y=costs)) + geom_point() + geom_line(color=&quot;blue&quot;) +
ggtitle(&quot;Costs vs iterations&quot;) + xlab(&quot;Iterations&quot;) + ylab(&quot;Loss&quot;)</span></code></pre>
</div>
<div>
<h1><img data-orig-file="https://gigadom.files.wordpress.com/2018/03/figr-1.jpg" data-orig-size="1202,614" data-medium-file="https://gigadom.files.wordpress.com/2018/03/figr-1.jpg?w=300" data-attachment-id="6451" data-image-meta="{" data-image-description="" src="https://gigadom.files.wordpress.com/2018/03/figr-1.jpg?w=450&h=345&fit=676%2C345" data-permalink="https://gigadom.wordpress.com/2018/03/23/deep-learning-from-first-principles-in-python-r-and-octave-part-5/figr-1/" data-large-file="https://gigadom.files.wordpress.com/2018/03/figr-1.jpg?w=450&amp;h=345&amp;fit=676%2C345" alt="" data-image-title="figR-1" sizes="(max-width: 676px) 100vw, 676px" data-comments-opened="1" class="wp-image-6451" data-recalc-dims="1"></h1>
<h3>5. Spiral dataset with Softmax activation – R</h3>
<p>The spiral data set used in the Python code above, is reused to test  multi-class classification with Softmax.</p>
<pre><code><span>source</span><span>(</span><span>&quot;DLfunctions5.R&quot;</span><span>)</span>
<span>Z</span> <span>&lt;-</span> <span>as.matrix</span><span>(</span><span>read.csv</span><span>(</span><span>&quot;spiral.csv&quot;</span>,<span>header</span><span>=</span><span>FALSE</span><span>)</span><span>)</span> 

<span># Setup the data</span>
<span>X</span> <span>&lt;-</span> <span>Z</span><span>[</span>,<span>1</span><span>:</span><span>2</span><span>]</span>
<span>y</span> <span>&lt;-</span> <span>Z</span><span>[</span>,<span>3</span><span>]</span>
<span>X</span> <span>&lt;-</span> <span>t</span><span>(</span><span>X</span><span>)</span>
<span>Y</span> <span>&lt;-</span> <span>t</span><span>(</span><span>y</span><span>)</span>

<span># Initialize number of features, number of hidden units in hidden layer and</span>
<span># number of classes</span>
<span>numFeats</span><span>&lt;-</span><span>2</span> <span># No features</span>
<span>numHidden</span><span>&lt;-</span><span>100</span> <span># No of hidden units</span>
<span>numOutput</span><span>&lt;-</span><span>3</span> <span># No of classes</span>

# Set the layer dimensions
<span>layersDimensions</span> <span>=</span> <span>c</span><span>(</span><span>numFeats</span>,<span>numHidden</span>,<span>numOutput</span><span>)</span>

# Perform gradient descent with relu activation unit for hidden layer
# and softmax activation in the output
<span>retvals</span> <span>=</span> <span>L_Layer_DeepModel</span><span>(</span><span>X</span>, <span>Y</span>, <span>layersDimensions</span>,
                            <span>hiddenActivationFunc</span><span>=</span><span>'relu'</span>,
                            <span>outputActivationFunc</span><span>=</span><span>&quot;softmax&quot;</span>,
                            <span>learningRate</span> <span>=</span> <span>0.5</span>,
                            <span>numIterations</span> <span>=</span> <span>9000</span>, 
                            <span>print_cost</span> <span>=</span> <span>True</span><span>)
#Plot cost vs iterations
iterations &lt;-seq(0,9000,1000)
costs=retvals$costs
df=data.frame(iterations,costs)
ggplot(df,aes(x=iterations,y=costs)) + geom_point() + geom_line(color=&quot;blue&quot;) +
ggtitle(&quot;Costs vs iterations&quot;) + xlab(&quot;Iterations&quot;) + ylab(&quot;Costs&quot;)</span></code></pre>
</div>
<div>
<h3>6. MNIST dataset with Softmax activation – R</h3>
<p>The code below executes a L – Layer Deep Learning network with Softmax output activation, to classify the 10 handwritten digits from MNIST with Stochastic Gradient Descent. The entire 60000 data set was used to train the data. R takes almost 8 hours to process this data set with a mini-batch size of 1000.  The use of ‘for’ loops is limited to iterating through epochs, mini batches and for creating the mini batches itself. All other code is vectorized. Yet, it seems to crawl. Most likely the use of ‘lists’ in R, to return multiple values is performance intensive. Some day, I will try to profile the code, and see where the issue is. However the code works!</p>
<p>Having said that, the Confusion Matrix in R dumps a lot of interesting statistics! There is a bunch of statistical measures for each class. For e.g. the Balanced Accuracy for the digits ‘6’ and ‘9’ is around 50%. Looks like, the classifier is confused by the fact that 6 is inverted 9 and vice-versa. The accuracy on the Test data set is just around 75%. I could have played around with the number of layers, number of hidden units, learning rates, epochs etc to get a much higher accuracy. But since each test took about 8+ hours, I may work on this, some other day!</p>
<pre><code><span><span>source</span><span>(</span><span>&quot;DLfunctions5.R&quot;</span><span>)</span>
<span>source</span><span>(</span><span>&quot;mnist.R&quot;</span><span>)
</span>#Load the mnist data
load_mnist<span>(</span><span>)</span>
show_digit<span>(</span>train<span>$</span>x<span>[</span><span>2</span>,<span>]</span><span>)
</span>#Set the layer dimensions
layersDimensions</span><span>=</span><span>c</span><span>(</span><span>784</span>, <span>15</span>,<span>9</span>, <span>10</span><span>)</span> <span># Works at 1500</span>
<span>x</span> <span>&lt;-</span> <span>t</span><span>(</span><span>train</span><span>$</span><span>x</span><span>)</span>
<span>X</span> <span>&lt;-</span> <span>x</span><span>[</span>,<span>1</span><span>:</span><span>60000</span><span>]</span>
<span>y</span> <span>&lt;-</span><span>train</span><span>$</span><span>y</span>
<span>y1</span> <span>&lt;-</span> <span>y</span><span>[</span><span>1</span><span>:</span><span>60000</span><span>]</span>
<span>y2</span> <span>&lt;-</span> <span>as.matrix</span><span>(</span><span>y1</span><span>)</span>
<span>Y</span><span>=</span><span>t</span><span>(</span><span>y2</span><span>)</span>
# Execute Stochastic Gradient Descent on the entire training set
# with Softmax activation
<span>retvalsSGD</span><span>=</span> <span>L_Layer_DeepModel_SGD</span><span>(</span><span>X</span>, <span>Y</span>, <span>layersDimensions</span>,
                            <span>hiddenActivationFunc</span><span>=</span><span>'relu'</span>,
                            <span>outputActivationFunc</span><span>=</span><span>&quot;softmax&quot;</span>,
                            <span>learningRate</span> <span>=</span> <span>0.01</span>,
                            <span>mini_batch_size</span> <span>=</span> <span>1000</span>, 
                            <span>num_epochs</span> <span>=</span> <span>1</span>, 
                            <span>print_cost</span> <span>=</span> <span>True</span><span>)</span></code></pre>
<p><img data-orig-file="https://gigadom.files.wordpress.com/2018/03/figr.jpg" data-orig-size="1200,586" data-medium-file="https://gigadom.files.wordpress.com/2018/03/figr.jpg?w=300" data-attachment-id="6448" data-image-meta="{" data-image-description="" src="https://gigadom.files.wordpress.com/2018/03/figr.jpg?w=450&h=330&fit=676%2C330" data-permalink="https://gigadom.wordpress.com/2018/03/23/deep-learning-from-first-principles-in-python-r-and-octave-part-5/figr/" data-large-file="https://gigadom.files.wordpress.com/2018/03/figr.jpg?w=450&amp;h=330&amp;fit=676%2C330" alt="" data-image-title="figR" sizes="(max-width: 676px) 100vw, 676px" data-comments-opened="1" class="wp-image-6448" data-recalc-dims="1"></p>
<pre><code><span># Compute the Confusion Matrix
<span>library</span><span>(</span>caret<span>)
<span>library</span>(e1071)</span>
predictions</span><span>=</span><span>predictProba</span><span>(</span><span>retvalsSGD</span><span>[</span><span>[</span><span>'parameters'</span><span>]</span><span>]</span>, <span>X</span>,<span>hiddenActivationFunc</span><span>=</span><span>'relu'</span>,
                   <span>outputActivationFunc</span><span>=</span><span>&quot;softmax&quot;</span><span>)</span>
<span>confusionMatrix</span><span>(</span><span>predictions</span>,<span>Y</span><span>)</span></code></pre>
<pre><code># Confusion Matrix on the Training set
> confusionMatrix(predictions,Y)
Confusion Matrix and Statistics

          Reference
Prediction    0    1    2    3    4    5    6    7    8    9
         0 5738    1   21    5   16   17    7   15    9   43
         1    5 6632   21   24   25    3    2   33   13  392
         2   12   32 5747  106   25   28    3   27   44 4779
         3    0   27   12 5715    1   21    1   20    1   13
         4   10    5   21   18 5677    9   17   30   15  166
         5  142   21   96  136   93 5306 5884   43   60  413
         6    0    0    0    0    0    0    0    0    0    0
         7    6    9   13   13    3    4    0 6085    0   55
         8    8   12    7   43    1   32    2    7 5703   69
         9    2    3   20   71    1    1    2    5    6   19

Overall Statistics
                                          
               Accuracy : 0.777           
                 95% CI : (0.7737, 0.7804)
    No Information Rate : 0.1124          
    P-Value [Acc > NIR] : &lt; 2.2e-16       
                                          
                  Kappa : 0.7524          
 Mcnemar's Test P-Value : NA              

Statistics by Class:

                     Class: 0 Class: 1 Class: 2 Class: 3 Class: 4 Class: 5 Class: 6
Sensitivity           0.96877   0.9837  0.96459  0.93215  0.97176  0.97879  0.00000
Specificity           0.99752   0.9903  0.90644  0.99822  0.99463  0.87380  1.00000
Pos Pred Value        0.97718   0.9276  0.53198  0.98348  0.95124  0.43513      NaN
Neg Pred Value        0.99658   0.9979  0.99571  0.99232  0.99695  0.99759  0.90137
Prevalence            0.09872   0.1124  0.09930  0.10218  0.09737  0.09035  0.09863
Detection Rate        0.09563   0.1105  0.09578  0.09525  0.09462  0.08843  0.00000
Detection Prevalence  0.09787   0.1192  0.18005  0.09685  0.09947  0.20323  0.00000
Balanced Accuracy     0.98314   0.9870  0.93551  0.96518  0.98319  0.92629  0.50000
                     Class: 7 Class: 8  Class: 9
Sensitivity            0.9713  0.97471 0.0031938
Specificity            0.9981  0.99666 0.9979464
Pos Pred Value         0.9834  0.96924 0.1461538
Neg Pred Value         0.9967  0.99727 0.9009521
Prevalence             0.1044  0.09752 0.0991500
Detection Rate         0.1014  0.09505 0.0003167
Detection Prevalence   0.1031  0.09807 0.0021667
Balanced Accuracy      0.9847  0.98568 0.5005701
</code></pre>
<pre><code><code># Confusion Matrix on the Training set</code> <span>xtest</span> <span>&lt;-</span> <span>t</span><span>(</span><span>test</span><span>$</span><span>x</span><span>)</span> <span>Xtest</span> <span>&lt;-</span> <span>xtest</span><span>[</span>,<span>1</span><span>:</span><span>10000</span><span>]</span> <span>ytest</span> <span>&lt;-</span><span>test</span><span>$</span><span>y</span> <span>ytest1</span> <span>&lt;-</span> <span>ytest</span><span>[</span><span>1</span><span>:</span><span>10000</span><span>]</span> <span>ytest2</span> <span>&lt;-</span> <span>as.matrix</span><span>(</span><span>ytest1</span><span>)</span> <span>Ytest</span><span>=</span><span>t</span><span>(</span><span>ytest2</span><span>)</span></code></pre>
<pre><code>
Confusion Matrix and Statistics

          Reference
Prediction    0    1    2    3    4    5    6    7    8    9
         0  950    2    2    3    0    6    9    4    7    6
         1    3 1110    4    2    9    0    3   12    5   74
         2    2    6  965   21    9   14    5   16   12  789
         3    1    2    9  908    2   16    0   21    2    6
         4    0    1    9    5  938    1    8    6    8   39
         5   19    5   25   35   20  835  929    8   54   67
         6    0    0    0    0    0    0    0    0    0    0
         7    4    4    7   10    2    4    0  952    5    6
         8    1    5    8   14    2   16    2    3  876   21
         9    0    0    3   12    0    0    2    6    5    1

Overall Statistics
                                          
               Accuracy : 0.7535          
                 95% CI : (0.7449, 0.7619)
    No Information Rate : 0.1135          
    P-Value [Acc > NIR] : &lt; 2.2e-16       
                                          
                  Kappa : 0.7262          
 Mcnemar's Test P-Value : NA              

Statistics by Class:

                     Class: 0 Class: 1 Class: 2 Class: 3 Class: 4 Class: 5 Class: 6
Sensitivity            0.9694   0.9780   0.9351   0.8990   0.9552   0.9361   0.0000
Specificity            0.9957   0.9874   0.9025   0.9934   0.9915   0.8724   1.0000
Pos Pred Value         0.9606   0.9083   0.5247   0.9390   0.9241   0.4181      NaN
Neg Pred Value         0.9967   0.9972   0.9918   0.9887   0.9951   0.9929   0.9042
Prevalence             0.0980   0.1135   0.1032   0.1010   0.0982   0.0892   0.0958
Detection Rate         0.0950   0.1110   0.0965   0.0908   0.0938   0.0835   0.0000
Detection Prevalence   0.0989   0.1222   0.1839   0.0967   0.1015   0.1997   0.0000
Balanced Accuracy      0.9825   0.9827   0.9188   0.9462   0.9733   0.9043   0.5000
                     Class: 7 Class: 8  Class: 9
Sensitivity            0.9261   0.8994 0.0009911
Specificity            0.9953   0.9920 0.9968858
Pos Pred Value         0.9577   0.9241 0.0344828
Neg Pred Value         0.9916   0.9892 0.8989068
Prevalence             0.1028   0.0974 0.1009000
Detection Rate         0.0952   0.0876 0.0001000
Detection Prevalence   0.0994   0.0948 0.0029000
Balanced Accuracy      0.9607   0.9457 0.4989384
</code></pre>
<h3>7. Random dataset with Sigmoid activation – Octave</h3>
<p>The Octave code below uses the random data set used by Python. The code below implements a L-Layer Deep Learning with Sigmoid Activation.</p>
<pre><code>
source(&quot;DL5functions.m&quot;)
# Read the data
data=csvread(&quot;data.csv&quot;);

X=data(:,1:2);
Y=data(:,3);
#Set the layer dimensions
layersDimensions = [2 9 7  1]; #tanh=-0.5(ok), #relu=0.1 best!
# Perform gradient descent 
[weights biases costs]=L_Layer_DeepModel(X', Y', layersDimensions,
                               hiddenActivationFunc='relu', 
                               outputActivationFunc=&quot;sigmoid&quot;,
                               learningRate = 0.1,
                               numIterations = 10000);
# Plot cost vs iterations
plotCostVsIterations(10000,costs);       
</code></pre>
<p><img data-orig-file="https://gigadom.files.wordpress.com/2018/03/fig1-o.png" data-orig-size="1200,900" data-medium-file="https://gigadom.files.wordpress.com/2018/03/fig1-o.png?w=300" data-attachment-id="6464" data-image-meta="{" data-image-description="" src="https://gigadom.files.wordpress.com/2018/03/fig1-o.png?w=450&h=507&fit=676%2C507" data-permalink="https://gigadom.wordpress.com/2018/03/23/deep-learning-from-first-principles-in-python-r-and-octave-part-5/fig1-o/" data-large-file="https://gigadom.files.wordpress.com/2018/03/fig1-o.png?w=450&amp;h=507&amp;fit=676%2C507" alt="" data-image-title="fig1-o" sizes="(max-width: 676px) 100vw, 676px" data-comments-opened="1" class="wp-image-6464" data-recalc-dims="1"></p>
<h3>8. Spiral dataset with Softmax activation – Octave</h3>
<p>The  code below uses the spiral data set used by Python above. The code below implements a L-Layer Deep Learning with Softmax Activation.</p>
<pre><code># Read the data
data=csvread(&quot;spiral.csv&quot;);

# Setup the data
X=data(:,1:2);
Y=data(:,3);

# Set the number of features, number of hidden units in hidden layer and number of classess
numFeats=2; #No features
numHidden=100; # No of hidden units
numOutput=3; # No of  classes
# Set the layer dimensions
layersDimensions = [numFeats numHidden  numOutput];  
#Perform gradient descent with softmax activation unit
[weights biases costs]=L_Layer_DeepModel(X', Y', layersDimensions,
                               hiddenActivationFunc='relu', 
                               outputActivationFunc=&quot;softmax&quot;,
                               learningRate = 0.1,
                               numIterations = 10000); 
</code></pre>
<p><img data-orig-file="https://gigadom.files.wordpress.com/2018/03/fig2-o.png" data-orig-size="1200,900" data-medium-file="https://gigadom.files.wordpress.com/2018/03/fig2-o.png?w=300" data-attachment-id="6466" data-image-meta="{" data-image-description="" src="https://gigadom.files.wordpress.com/2018/03/fig2-o.png?w=450&h=507&fit=676%2C507" data-permalink="https://gigadom.wordpress.com/2018/03/23/deep-learning-from-first-principles-in-python-r-and-octave-part-5/fig2-o/" data-large-file="https://gigadom.files.wordpress.com/2018/03/fig2-o.png?w=450&amp;h=507&amp;fit=676%2C507" alt="" data-image-title="fig2-o" sizes="(max-width: 676px) 100vw, 676px" data-comments-opened="1" class="wp-image-6466" data-recalc-dims="1"></p>
<h3>9. MNIST dataset with Softmax activation – Octave</h3>
<p>The code below implements a L-Layer Deep Learning Network in Octave with Softmax output activation unit, for classifying the 10 handwritten digits in the MNIST dataset. Unfortunately, Octave can only index to around 10000 training at a time,  and I was getting an error ‘error: out of memory or dimension too large for Octave’s index type error: called from…’, when I tried to create a batch size of 20000.  So I had to come with a work around to create a batch size of 10000 (randomly) and then use a mini-batch of 1000 samples and execute Stochastic Gradient Descent. The performance was good. Octave takes about 15 minutes, on a batch size of 10000 and a mini batch of 1000.</p>
<p>I thought if the performance was not good, I could iterate through these random batches and refining the gradients as follows</p>
<pre><code># Pseudo code that could be used since Octave only allows 10K batches
# at a time
# Randomly create weights
[weights biases] = initialize_weights()
for i=1:k
    # Create a random permutation and create a random batch
    permutation = randperm(10000);
    X=trainX(permutation,:);
    Y=trainY(permutation,:);
    # Compute weights from SGD and update weights in the next batch update
    [weights biases costs]=L_Layer_DeepModel_SGD(X,Y,mini_bactch=1000,weights, biases,...);
    ...
endfor</code></pre>
<pre><code># Load the MNIST data
load('./mnist/mnist.txt.gz'); 
#Create a random permutatation from 60K
permutation = randperm(10000);
disp(length(permutation));

# Use this 10K as the batch
X=trainX(permutation,:);
Y=trainY(permutation,:);

# Set layer dimensions
layersDimensions=[784, 15, 9, 10];

# Run Stochastic Gradient descent with batch size=10K and mini_batch_size=1000
[weights biases costs]=L_Layer_DeepModel_SGD(X', Y', layersDimensions,
                       hiddenActivationFunc='relu', 
                       outputActivationFunc=&quot;softmax&quot;,
                       learningRate = 0.01,
                       mini_batch_size = 2000, num_epochs = 5000);   
</code></pre>
<p><img data-orig-file="https://gigadom.files.wordpress.com/2018/03/figure3-o.png" data-orig-size="1200,900" data-medium-file="https://gigadom.files.wordpress.com/2018/03/figure3-o.png?w=300" data-attachment-id="6468" data-image-meta="{" data-image-description="" src="https://gigadom.files.wordpress.com/2018/03/figure3-o.png?w=450&h=507&fit=676%2C507" data-permalink="https://gigadom.wordpress.com/2018/03/23/deep-learning-from-first-principles-in-python-r-and-octave-part-5/figure3-o/" data-large-file="https://gigadom.files.wordpress.com/2018/03/figure3-o.png?w=450&amp;h=507&amp;fit=676%2C507" alt="" data-image-title="figure3-o" sizes="(max-width: 676px) 100vw, 676px" data-comments-opened="1" class="wp-image-6468" data-recalc-dims="1"></p>
<h4><strong>9. Final thoughts</strong></h4>
<p>Here are some of my final thoughts after working on Python, R and Octave in this series and in other projects<br>
1. Python, with its highly optimized numpy library, is ideally suited for creating Deep Learning Models, which have a lot of matrix manipulations. Python is a real workhorse when it comes to Deep Learning computations.<br>
2. R is somewhat clunky in comparison to its cousin Python in handling matrices or in returning multiple values. But R’s statistical libraries, dplyr, and ggplot are really superior to the Python peers. Also, I find R handles  dataframes,  much better than Python.<br>
3. Octave is a no-nonsense,minimalist language which is very efficient in handling matrices. It is ideally suited for implementing Machine Learning and Deep Learning from scratch. But Octave has its problems and cannot handle large matrix sizes, and also lacks the statistical libaries of R and Python. They possibly exist in its sibling, Matlab</p>
<p>Feel free to clone/download the code from  GitHub at <a rel="nofollow" href="https://github.com/tvganesh/DeepLearning-Part5" target="_blank">DeepLearning-Part5</a>.</p>
<h4>Conclusion</h4>
<p>Building a Deep Learning Network from scratch is quite challenging, time-consuming but nevertheless an exciting task.  While the statements in the different languages for manipulating matrices, summing up columns, finding columns which have ones don’t take more than a single statement, extreme care has to be taken to ensure that the statements work well for any dimension.  The lessons learnt from creating L -Layer Deep Learning network  are many and well worth it. Give it a try!</p>
<p>Hasta la vista! I’ll be back, so stick around!<br>
Watch this space!</p>
<p><strong>References</strong><br>
1. <a rel="nofollow" href="https://www.coursera.org/specializations/deep-learning" target="_blank">Deep Learning Specialization</a><br>
2. <a rel="nofollow" href="https://www.coursera.org/learn/neural-networks" target="_blank">Neural Networks for Machine Learning</a><br>
3. <a rel="nofollow" href="http://cs231n.github.io/neural-networks-case-study/" target="_blank">CS231 Convolutional Neural Networks for Visual Recognition</a><br>
4. <a rel="nofollow" href="https://eli.thegreenplace.net/2016/the-softmax-function-and-its-derivative/" target="_blank">Eli Bendersky’s Website – The Softmax function and its derivative</a></p>
<p>Also see<br>
1. <a rel="nofollow" href="https://gigadom.wordpress.com/2017/12/05/my-book-practical-machine-learning-with-r-and-python-on-amazon/" target="_blank">My book ‘Practical Machine Learning with R and Python’ on Amazon</a><br>
2. <a rel="nofollow" href="https://gigadom.wordpress.com/2013/07/24/presentation-on-wireless-technologies-part-1/" target="_blank">Presentation on Wireless Technologies – Part 1</a><br>
3. <a rel="nofollow" href="https://gigadom.wordpress.com/2016/06/05/exploring-quantum-gate-operations-with-qcsimulator/" target="_blank">Exploring Quantum Gate operations with QCSimulator</a><br>
4. <a rel="nofollow" href="https://gigadom.wordpress.com/2014/10/11/whats-up-watson-using-ibm-watsons-qaapi-with-bluemix-nodeexpress-part-1/" target="_blank">What’s up Watson? Using IBM Watson’s QAAPI with Bluemix, NodeExpress – Part 1</a><br>
5. <a rel="nofollow" href="https://gigadom.wordpress.com/2015/04/04/tws-4-gossip-protocol-epidemics-and-rumors-to-the-rescue/" target="_blank">TWS-4: Gossip protocol: Epidemics and rumors to the rescue</a><br>
6. <a rel="nofollow" href="https://gigadom.wordpress.com/2015/08/02/cricketr-plays-the-odis/" target="_blank">cricketr plays the ODIs!</a><br>
7. <a rel="nofollow" href="https://gigadom.wordpress.com/2013/07/05/is-it-an-animal-is-it-an-insect-in-android/" target="_blank">“Is it an animal? Is it an insect?” in Android</a><br>
8. <a rel="nofollow" href="https://gigadom.wordpress.com/2017/12/16/the-3rd-paperback-edition-of-my-books-on-cricket-on-amazon/" target="_blank">The 3rd paperback &amp; kindle editions of my books on Cricket, now on Amazon</a><br>
9. <a rel="nofollow" href="https://gigadom.wordpress.com/2012/05/11/deblurring-with-opencv-weiner-filter-reloaded/" target="_blank">Deblurring with OpenCV: Weiner filter reloaded</a><br>
10. <a rel="nofollow" href="https://gigadom.wordpress.com/2017/01/05/googlyplus-yorkr-analyzes-ipl-players-teams-matches-with-plots-and-tables/" target="_blank">GooglyPlus: yorkr analyzes IPL players, teams, matches with plots and tables</a></p>
<p>To see all posts click <a rel="nofollow" href="https://gigadom.wordpress.com/aa-2/" target="_blank">Index of Posts</a></p>
</div>
<p> </p>
	<img alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/VP54IQ3eM-0" height="1">