<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/image-recognition-tutorial-in-r-using-deep-convolutional-neural-networks-mxnet-package/"></div></div><div><a data-url="https://www.r-bloggers.com/image-recognition-tutorial-in-r-using-deep-convolutional-neural-networks-mxnet-package/" data-counturl="https://www.r-bloggers.com/image-recognition-tutorial-in-r-using-deep-convolutional-neural-networks-mxnet-package/" data-count="horizontal" data-text="Image recognition tutorial in R using deep convolutional neural networks (MXNet package)" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://firsttimeprogrammer.blogspot.com/2016/08/image-recognition-tutorial-in-r-using.html"> The Beginner Programmer</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>This is a detailed tutorial on image recognition in R using a deep convolutional neural network provided by the <strong><a target="_blank" href="https://github.com/dmlc/mxnet">MXNet package</a></strong>. After a <a target="_blank" href="http://firsttimeprogrammer.blogspot.com/2016/07/image-recognition-in-r-using.html">short post</a> I wrote some times ago I received a lot of requests and emails for a much more detailed explanation, therefore I decided to write this tutorial. This post will show a reproducible example on how to get 97.5% accuracy score on a faces recognition task in R. </p>
<p><a target="_blank" href="https://i1.wp.com/lh3.googleusercontent.com/-nEI6wVVWB2Q/V6UHVnx2WTI/AAAAAAAABtE/eLuJS_qyDC0/s1600-h/my_convolutional_neural_network%25255B6%25255D.jpg?ssl=1"><img title="my_convolutional_neural_network" alt="my_convolutional_neural_network" src="https://i1.wp.com/lh3.googleusercontent.com/-h55l2vVX1_E/V6UHV_zxf_I/AAAAAAAABtI/jif5V_AL_wE/my_convolutional_neural_network_thumb%25255B3%25255D.jpg?resize=456%2C131&ssl=1" border="0" data-recalc-dims="1"></a></p>
<h2></h2>
<p> <a name="more"></a><br>
<h2>Premises</h2>
<p>I feel some premises are necessary. I’m writing this <strong>tutorial</strong> with two main objectives.<br>The first one is to provide a fully reproducible example to everyone; the second objective is to provide a, hopefully, clear explanation to the most frequent questions I received via email on <a target="_blank" href="http://firsttimeprogrammer.blogspot.com/2016/07/image-recognition-in-r-using.html">the old post</a>. Please be aware that this is just how I decided to tackle this particular problem, this is certainly not the only way to solve it, and most certainly it is not the best. If you have any suggestion to improve the model or the process, or should you spot any mistake, please do leave a comment.</p>
<h2>Requirements</h2>
<p>I’m going to use both <strong>Python 3.x</strong> (for getting the data and some preprocessing) and <strong>R</strong> (for the core of the tutorial), so make sure to have both installed. The package requirements for R are the following:</p>
<ol>
<li><a target="_blank" href="https://github.com/dmlc/mxnet/blob/master/docs/how_to/build.md">MXNet</a>. This package will provide you with the model we are going to be using in this tutorial, namely a deep convolutional neural network. You don’t need the GPU version, CPU will suffice for this task although it could be slower. If you feel like it, then go for the GPU version.
<li><a target="_blank" href="https://bioconductor.org/packages/release/bioc/html/EBImage.html">EBImage</a>. This package provides a wide variety of tools to work with images. It is a pleasure to work on images using this package, the documentation is crystal clear and pretty straightforward.</li>
</ol>
<p>As for Python 3.x please make sure to install both<strong> </strong><a target="_blank" href="http://www.numpy.org/"><strong>Numpy</strong></a> and<strong> </strong><a target="_blank" href="http://scikit-learn.org/stable/"><strong>Scikit-learn</strong></a>. I suggest to install the <strong><a target="_blank" href="https://www.continuum.io/downloads">Anaconda</a></strong> distribution which already has installed some commonly used packages for <strong>data science</strong> and <strong>machine learning</strong>.</p>
<p>Once you have all these things installed and running, you are set to go.</p>
<h2>The dataset</h2>
<p>I am going to use the <a target="_blank" href="http://scikit-learn.org/stable/datasets/olivetti_faces.html">Olivetti faces dataset</a><sup>1</sup>. This dataset is a collection of 64×64 pixel 0-256 greyscale images.</p>
<p>The dataset contains a total of 400 images of 40 subjects. With just 10 samples for each subject it is usually used for <strong>unsupervised </strong>or <strong>semi-supervised</strong> algorithms, but I’m going to try my best with the selected <strong>supervised </strong>method.</p>
<p>First of all, you need to scale the images in the 0-1 range. This is automatically done by the function we are going to use to download the dataset, so you do not need to worry about it that much, just be aware that it has already been done for you. Should you use your own images be sure to <strong>scale</strong> them down in the 0-1 range (or –1,1 range, although the first seems work better with neural networks in my experience). This below is the Python script you need to run in order to download the dataset. Just change the paths to your selected paths and then run it either from your IDE or the terminal.</p>
<p>
<p>What this piece of code does is basically download the data, reshape the X datapoints (the images) and then save the numpy arrays to a .csv file.</p>
<p>As you can see, the x array is a tensor (tensor is a fancy name for a multidimensional matrix) of shape (400, 64, 64): this means that the x array contains 400 samples of 64×64 matrices (read images). When in doubt about these things, just print out the first elements of the tensor and try to figure out the structure of the data with what you know. For instance, we know from the dataset description that we have 400 samples and that each image is 64×64 pixel. We flatten the x tensor into a matrix of shape  400×4096. That is, each 64×64 matrix (image) is now converted (flattened) to a row vector of length 4096.</p>
<p>As for y, y is already a simple column vector of size 400. No need to reshape it.</p>
<p>Take a look at the generated .csv and check that everything makes sense to you.</p>
<h2>Some more preprocessing with R</h2>
<p>Now we are going to use <strong>EBImage</strong> to resize each image to 28×28 pixel and generate the training and testing datasets. You may ask why I am resizing the images, well, for some reason my machine does not like 64×64 pixel images and my PC crash whenever I run the model with the data. Not good. But that’s ok since we can get good results with smaller images too (you can try running the model with the 64×64 size images if your PC does not crash though). Let’s go on now:</p>
<p>
<p>This part of the tutorial should be pretty self explanatory, if you are not sure on what is the output, I suggest taking a look at the <strong>rs_df </strong>dataframe. It should be a 400×785 dataframe as follows:</p>
<p>label, pixel1, pixel2, … , pixel784<br>0, 0.2, 0.3, … ,0.1</p>
<h2>Building the model</h2>
<p>Now for the fun part, let’s build the model. Below you can find the script I used to train and test the model. After the script you can find my comments and explanations on the code.</p>
<p>
<p>After having loaded the training and testing dataset, I convert each dataframe to a numeric matrix using the <em>data.matrix</em> function. Remember that the first column of the data represents the labels associated with each image. Be sure to remove the labels from <em>train_array</em> and <em>test_array</em>. Then, after having separated the predictors from the labels, you need to tell MXNet the shape of the data. This is what I did at line 19 with the following piece of code “dim(train_array) &lt;- c(28, 28, 1, ncol(train_x))” for the training array and at line 24 for the test arrray. By doing this, we are essentially telling the model that the training data is made of ncol(train_x) samples (360 images) of shape 28×28. The number 1 signals that the images are greyscale, ie they have only 1 channel. If the images were RGB then the 1 should have been replaced by a 3 since in that case each image would have 3 channels.</p>
<p>As far as the model structure is concerned, this is a  variation of the LeNet model using hyperbolic tangent instead of “Relu” as activation function, 2 convolutional layers, 2 pooling layers, 2 fully connected layer, and a typical softmax output.</p>
<p>Each <strong>convolutional layer</strong> is using a 5×5 kernel and applying a fixed number of filters, check <a target="_blank" href="https://www.youtube.com/watch?v=BFdMrDOx_CM">this awesome video</a> for some qualitative insight into convolutional layers. The <strong>pooling layers</strong> apply a classical “max pooling” approach.</p>
<p>During my tests <strong>tanh</strong> seemd to work far better than sigmoid and Relu but you can try and use the other activation functions if you want.</p>
<p>As for the model <strong>hyperparameters</strong>, the learning rate is a little higher than usual but it turns out that it works fine, while the selected number of epochs is 480. Batch size of 40 seems to work fine. These hyperparameters were found out from many trials and error. As far as I know I could have performed a grid search at best, but I did not want to over complicate the code and therefore I just used the classical trial and error approach.</p>
<p>At the end you should get 0.975 accuracy.</p>
<h2>Conclusions</h2>
<p>All in all, this model was fairly easy to set up and run. When running on CPU it takes about 4-5 minutes to train which is a bit long if you want to make some experiments but it is reasonable to work with.</p>
<p>Considering the fact that we did not do any feature engineering and just made some simple and ordinary preprocessing steps, I believe the result achieved is quite good. Of course, in case we would like to get a better grasp on the “true” accuracy,  we would need to perform some cross validation procedures (that will inevitably eat up a lot of computing time <img alt="Smile" src="https://i0.wp.com/lh3.googleusercontent.com/-C9fbfj6H5TI/V6UHWH3E9lI/AAAAAAAABtM/_q1i38Kt3Ps/wlEmoticon-smile%25255B2%25255D.png?w=456&ssl=1" data-recalc-dims="1">). </p>
<p>Thank you for reading this far, I hope this tutorial helped you understanding how to set up and run this particular model. </p>
<p>
<hr> Dataset source and credits:
<p><sup>1</sup>Olivetti faces dataset was made by AT&amp;T Laboratories Cambridge.</p>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="https://www.r-bloggers.com/image-recognition-tutorial-in-r-using-deep-convolutional-neural-networks-mxnet-package/"></div></div><div><a data-url="https://www.r-bloggers.com/image-recognition-tutorial-in-r-using-deep-convolutional-neural-networks-mxnet-package/" data-counturl="https://www.r-bloggers.com/image-recognition-tutorial-in-r-using-deep-convolutional-neural-networks-mxnet-package/" data-count="vertical" data-text="Image recognition tutorial in R using deep convolutional neural networks (MXNet package)" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://firsttimeprogrammer.blogspot.com/2016/08/image-recognition-tutorial-in-r-using.html"> The Beginner Programmer</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/?s=Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/r3CO9FpYgTc"></a></div>