<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/deep-learning-in-r-2/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.rblog.uni-freiburg.de/2017/02/07/deep-learning-in-r/"> R Blog</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p> </p>
<div>
<div>
<h4><em>Oksana Kutkina, Stefan Feuerriegel</em></h4>
<h4><em>March 7, 2016</em></h4>
</div>
<div>
<h2>Introduction</h2>
<p>Deep learning is a recent trend in machine learning that models highly non-linear representations of data. In the past years, deep learning has gained a tremendous momentum and prevalence for a variety of applications <span>(Wikipedia 2016a)</span>. Among these are image and speech recognition, driverless cars, natural language processing and many more. Interestingly, the majority of mathematical concepts for deep learning have been known for decades. However, it is only through several recent developments that the full potential of deep learning has been unleashed <span>(Nair and Hinton 2010; Srivastava et al. 2014)</span>.</p>
<p>Previously, it was hard to train artificial neural networks due to vanishing gradients and overfitting problems. Both problems are now solved by using different activation functions, dropout regularization and a massive amount of training data. For instance, the Internet can nowadays be utilized to retrieve large volumes of both labeled and unlabeled data. In addition, the availability of GPUs and GPGPUs has made computations much cheaper and faster.</p>
<p>Today, deep learning has shown itself to be very effective for almost any task which requires machine learning. However, it is particularly suited to complex, hierarchical data. Its underlying artificial neural network models highly non-linear representations; these are usually composed of multiple layers together with non-linear transformations and tailored architectures. A typical representation of a deep neural network is depicted in Figure 1.</p>
<div><img sizes="(max-width: 300px) 85vw, 300px" alt="" class="wp-image-23" src="https://i0.wp.com/www.rblog.uni-freiburg.de/wp-content/uploads/2016/11/Deep_Neural_Network-300x236.png?resize=300%2C236" data-recalc-dims="1"><br>
Figure 1. Model of a deep neural network.</div>
<p>The success of deep learning has led to a wide range of frameworks and libraries for various programming languages. Examples include Caffee, Theano, Torch and Tensor Flow, amongst others. This blog entry aims to provide an overview and comparison of different deep learning packages available for the programming language R. We compare performance and ease-of-use across different datasets.</p>
</div>
<div>
<h2>Packages for deep learning in R</h2>
<p>The R programming language has gained considerable popularity among statisticians and data miners for its ease-of-use, as well as its sophisticated visualizations and analyses. With the advent of the deep learning era, the support for deep learning in R has grown ever since, with an increasing number of packages becoming available. This section presents an overview on deep learning in R as provided by the following packages: MXNetR, darch, deepnet, H2O and deepr.</p>
<p>First of all, we note that the underlying learning algorithms greatly vary from one package to another. As such, Table 1 shows a list of the available methods/architectures in each of the packages.</p>
<table>
<caption>
<p>Table 1. List of available deep learning methods across the R packages.</p>
</caption>
<thead>
<tr>
<th align="left">Package</th>
<th align="left">Available architectures of neural networks</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left">MXNetR</td>
<td align="left">Feed-forward neural network, convolutional neural network (CNN)</td>
</tr>
<tr>
<td align="left">darch</td>
<td align="left">Restricted Boltzmann machine, deep belief network</td>
</tr>
<tr>
<td align="left">deepnet</td>
<td align="left">Feed-forward neural network, restricted Boltzmann machine, deep belief network, stacked autoencoders</td>
</tr>
<tr>
<td align="left">H2O</td>
<td align="left">Feed-forward neural network, deep autoencoders</td>
</tr>
<tr>
<td align="left">deepr</td>
<td align="left">Simplify some functions from H2O and deepnet packages</td>
</tr>
</tbody>
</table>
<div>
<h3><strong>Package “MXNetR”</strong></h3>
<p>The MXNetR package is an interface of the MXNet library written in C++. It contains feed-forward neural networks and convolutional neural networks (CNN) <span>(MXNetR 2016a)</span>. It also allows one to construct customized models. This package is distributed in two versions: CPU only or GPU version. The former CPU version can be easily installed directly from inside R, whereas the latter GPU version depends on 3rd party libraries like cuDNN and requires building the library from its source code <span>(MXNetR 2016b)</span>.</p>
<p>A feed-forward neural network (multi-layer perceptron) can be built in MXNetR with the function call:</p>
<pre><code>mx.mlp(data, label, hidden_node=1, dropout=NULL, activation=”tanh”, out_activation=”softmax”, device=mx.ctx.default(),…)</code></pre>
<p>The parameters are as follows:</p>
<ul>
<li><code>data</code> – input matrix</li>
<li><code>label</code> – training labels</li>
<li><code>hidden_node</code> – a vector containing the number of hidden nodes in each hidden layer</li>
<li><code>dropout</code> – a number in [0,1) containing the dropout ratio from the last hidden layer to the output layer</li>
<li><code>activation</code> – either a single string or a vector containing the names of activation functions. Valid values are {<code>'relu'</code>, <code>'sigmoid'</code>, <code>'softrelu'</code>, <code>'tanh'</code>}</li>
<li><code>out_activation</code> – a single string containing the name of the output activation function. Valid values are {<code>'rmse'</code>, <code>'sofrmax'</code>, <code>'logistic'</code>}</li>
<li><code>device</code> – whether to train on <code>mx.cpu</code> (default) or <code>mx.gpu</code></li>
<li><code>...</code> – other parameters passing to <code>mx.model.FeedForward.create</code></li>
</ul>
<p>Function <code>mx.model.FeedForward.create</code> is used internally in <code>mx.mpl</code> and takes the following parameters:</p>
<ul>
<li><code>symbol</code> – the symbolic configuration of the neural network</li>
<li><code>y</code> – array of labels</li>
<li><code>x</code> – training data</li>
<li><code>ctx</code> – context, i.e. a device (CPU/GPU) or list of devices (multiple CPUs or GPUs)</li>
<li><code>num.round</code> – number of iterations to train the model</li>
<li><code>optimizer</code> – string (default is <code>'sgd'</code>)</li>
<li><code>initializer</code> – initialization scheme for parameters</li>
<li><code>eval.data</code> – validation set used during the process</li>
<li><code>eval.metric</code> – evaluation function on the results</li>
<li><code>epoch.end.callback</code> – callback when iteration ends</li>
<li><code>batch.end.callback</code> – callback when one mini-batch iteration ends</li>
<li><code>array.batch.size</code> – batch size used for array training</li>
<li><code>array.layout</code> – can be {<code>'auto'</code>, <code>'colmajor'</code>, <code>'rowmajor'</code>}</li>
<li><code>kvstore</code> – synchronization scheme for multiple devices</li>
</ul>
<p><strong>Sample call:</strong></p>
<pre><code>model &lt;- mx.mlp(train.x, train.y, hidden_node=c(128,64), out_node=2, activation=&quot;relu&quot;, out_activation=&quot;softmax&quot;,num.round=100, array.batch.size=15, learning.rate=0.07, momentum=0.9, device=mx.cpu())</code></pre>
<p>To use the trained model afterwards, we simply need to invoke the function <code>predict()</code> specifying the <code>model</code> as the first parameter and <code>testset</code> as the second:</p>
<pre><code>preds = predict(model, testset)</code></pre>
<p>The function <code>mx.mlp()</code> is essentially a proxy to the more flexible but lengthy process of defining a neural network by using ‘Symbol’ system of MXNetR. The equivalent of the previous network in symbolic definition will be:</p>
<pre><code>data &lt;- mx.symbol.Variable(&quot;data&quot;) fc1 &lt;- mx.symbol.FullyConnected(data, num_hidden=128) act1 &lt;- mx.symbol.Activation(fc1, name=&quot;relu1&quot;, act_type=&quot;relu&quot;) fc2 &lt;- mx.symbol.FullyConnected(act1, name=&quot;fc2&quot;, num_hidden=64) act2 &lt;- mx.symbol.Activation(fc2, name=&quot;relu2&quot;, act_type=&quot;relu&quot;) fc3 &lt;- mx.symbol.FullyConnected(act2, name=&quot;fc3&quot;, num_hidden=2) lro &lt;- mx.symbol.SoftmaxOutput(fc3, name=&quot;sm&quot;) model2 &lt;- mx.model.FeedForward.create(lro, X=train.x, y=train.y, ctx=mx.cpu(), num.round=100, array.batch.size=15, learning.rate=0.07, momentum=0.9)</code></pre>
<p>When the architecture of the network is finally created, MXNetR provides a simple way to graphically inspect it using the following function call:</p>
<pre><code>graph.viz(model$symbol$as.json())</code></pre>
<p><img alt="" src="https://i1.wp.com/www.rblog.uni-freiburg.de/wp-content/uploads/2016/11/computation_graph_1.png?w=456" data-recalc-dims="1"></p>
<p> </p>
<pre><code>graph.viz(model2$symbol$as.json())</code></pre>
<p><img sizes="(max-width: 283px) 85vw, 283px" alt="" class="wp-image-32" src="https://i0.wp.com/www.rblog.uni-freiburg.de/wp-content/uploads/2016/11/computation_graph_2.png?fit=450%2C600" data-recalc-dims="1"></p>
<p> </p>
<p>Here, the parameter is the trained model represented by the symbol. The first network is constructed by <code>mx.mlp()</code> and the second using the symbol system.</p>
<p>The definition goes layer-by-layer from input to output, while also allowing for a different number of neurons and specific activation functions for each layer separately. Additional options are available via <code>mx.symbol</code>: <code>mx.symbol.Convolution</code>, which applies convolution to the input and then adds a bias. It can create convolutional neural networks. The reverse is <code>mx.symbol.Deconvolution</code>, which is usually used in segmentation networks along with <code>mx.symbol.UpSampling</code> in order to reconstruct the pixel-wise classification of an image. Another type of layer used in CNNs is <code>mx.symbol.Pooling</code>; this essentially reduces the data by usually picking signals with the highest response. The layer <code>mx.symbol.Flatten</code> is needed to link convolutional and pooling layers to a fully connected network. Additionally, <code>mx.symbol.Dropout</code> can be used to cope with the overfitting problem. It takes as a parameter <code>previous_layer</code> and a float value <code>fraction</code> of the input that is dropped.</p>
<p>As we can see, MXNetR can be used for quick design of standard multi-layer perceptrons with the function <code>mx.mlp()</code> or for more extensive experiments regarding symbolic representation.</p>
<p>Example of LeNet network:</p>
<pre><code>data &lt;- mx.symbol.Variable('data') conv1 &lt;- mx.symbol.Convolution(data=data, kernel=c(5,5), num_filter=20) tanh1 &lt;- mx.symbol.Activation(data=conv1, act_type=&quot;tanh&quot;) pool1 &lt;- mx.symbol.Pooling(data=tanh1, pool_type=&quot;max&quot;, kernel=c(2,2), stride=c(2,2)) conv2 &lt;- mx.symbol.Convolution(data=pool1, kernel=c(5,5), num_filter=50) tanh2 &lt;- mx.symbol.Activation(data=conv2, act_type=&quot;tanh&quot;) pool2 &lt;- mx.symbol.Pooling(data=tanh2, pool_type=&quot;max&quot;, kernel=c(2,2), stride=c(2,2)) flatten &lt;- mx.symbol.Flatten(data=pool2) fc1 &lt;- mx.symbol.FullyConnected(data=flatten, num_hidden=500) tanh3 &lt;- mx.symbol.Activation(data=fc1, act_type=&quot;tanh&quot;) fc2 &lt;- mx.symbol.FullyConnected(data=tanh3, num_hidden=10) lenet &lt;- mx.symbol.SoftmaxOutput(data=fc2) model &lt;- mx.model.FeedForward.create(lenet, X=train.array, y=train.y, ctx=device.cpu, num.round=5, array.batch.size=100, learning.rate=0.05, momentum=0.9)</code></pre>
<p>Altogether, the MXNetR package is highly flexible, while supporting both multiple CPUs and multiple GPUs. It has a shortcut to build standard feed-forward networks, but also grants flexible functionality to build more complex, customized networks such as CNN LeNet.</p>
</div>
<div>
<h3><strong>Package “darch”</strong></h3>
<p>The darch package <span>(darch 2015)</span> implements the training of deep architectures, such as deep belief networks, which consist of layer-wise pre-trained restricted Boltzmann machines. The package also entails backpropagation for fine-tuning and, in the latest version, makes pre-training optional.</p>
<p>Training of a Deep Belief Network is performed via <code>darch()</code> function.</p>
<p><strong>Sample call:</strong></p>
<pre><code>darch  &lt;- darch(train.x, train.y,                 rbm.numEpochs = 0,                 rbm.batchSize = 100,                 rbm.trainOutputLayer = F,                 layers = c(784,100,10),                 darch.batchSize = 100,                 darch.learnRate = 2,                 darch.retainData = F,                 darch.numEpochs = 20 )</code></pre>
<p>This function takes several parameters with the most important ones as follows:</p>
<ul>
<li><code>x</code> – input data</li>
<li><code>y</code> – target data</li>
<li><code>layers</code> – vector containing one integer for the number of neurons in each layer (including input and output layers)</li>
<li><code>rbm.batchSize</code> – pre-training batch size</li>
<li><code>rbm.trainOutputLayer</code> – boolean used in pre-training. If true, the output layer of RBM is trained as well</li>
<li><code>rbm.numCD</code> – number of full steps for which contrastive divergence is performed</li>
<li><code>rbm.numEpochs</code> – number of epochs for pre-training</li>
<li><code>darch.batchSize</code> – fine-tuning batch size</li>
<li><code>darch.fineTuneFunction</code>– fine-tuning function</li>
<li><code>darch.dropoutInput</code> – dropout rate on the network input</li>
<li><code>darch.dropoutHidden</code> – dropout rate on the hidden layers</li>
<li><code>darch.layerFunctionDefault</code> – default activation function for DBN, available options are {<code>'sigmoidUnitDerivative'</code>, <code>'binSigmoidUnit'</code>, <code>'linearUnitDerivative'</code>, <code>'linearUnit'</code>, <code>'maxoutUnitDerivative'</code>, <code>'sigmoidUnit'</code>, <code>'softmaxUnitDerivative'</code>, <code>'softmaxUnit'</code>, <code>'tanSigmoidUnitDerivative'</code>, <code>'tanSigmoidUnit'</code> }</li>
<li><code>darch.stopErr</code> – stops training if the error is smaller or equal than a threshold</li>
<li><code>darch.numEpochs</code> – number of epochs for fine-tuning</li>
<li><code>darch.retainData</code> – boolean, indicates weather to store the training data in darch instance after training</li>
</ul>
<p>Based on the previous parameters, we can train our model resulting in an object <code>darch</code>. We can later apply this to a test dataset <code>test.x</code> to make predictions. In that case, an additional parameter <code>type</code> specifies the output type of the prediction. For example, it can be <code>‘raw’</code> to give probabilities, <code>‘bin’</code> for binary vectors and <code>‘class’</code> for class labels. Finally, the prediction is made when calling <code>predict()</code> as follows:</p>
<pre><code>predictions &lt;- predict(darch, test.x, type=&quot;bin&quot;)</code></pre>
<p>Overall, the basic usage of darch is very simple. It requires only one function to train the network. But on the other hand, the package is limited to deep belief networks, which usually require much more extensive training.</p>
</div>
<div>
<h3><strong>Package “deepnet”</strong></h3>
<p>deepnet <span>(deepnet 2015)</span> is a relatively small, yet quite powerful package with variety of architectures to pick from. It can train a feed-forward network using the function <code>nn.train()</code> or initialize weights for the deep belief network with <code>dbn.dnn.train()</code>. This function internally uses <code>rbm.train()</code> to train a restricted Boltzmann machine (which can also be used individually). Furthermore, deepnet can also handle stacked autoencoders via <code>sae.dnn.train()</code>.</p>
<p><strong>Sample call</strong> (for <code>nn.train()</code>):</p>
<pre><code>nn.train(x, y, initW=NULL, initB=NULL, hidden=c(50,20), activationfun=&quot;sigm&quot;, learningrate=0.8, momentum=0.5, learningrate_scale=1, output=&quot;sigm&quot;, numepochs=3, batchsize=100, hidden_dropout=0, visible_dropout=0)</code></pre>
<p>One can set initial weights <code>initW</code> and weights <code>initB</code> which are otherwise randomly generated. In addition, <code>hidden</code> controls the number of units in the hidden layers, whereas <code>activationfun</code> specifies the activation function of the hidden layers (can be <code>‘sigm’</code>, <code>‘linear’</code> or <code>‘tanh’</code>), as well as of the output layer (can be <code>‘sigm’</code>, <code>‘linear’</code>, <code>‘softmax’</code>).</p>
<p>As an alternative, the following example trains a neural network where the weights are initialized by a deep belief network (via <code>dbn.dnn.train()</code>). The difference is mainly in the contrastive divergence algorithm that trains the restricted Boltzmann machines. It is set via <code>cd</code>, giving the number of iterations for Gibbs sampling inside the learning algorithm.</p>
<pre><code>dbn.dnn.train(x, y, hidden=c(1), activationfun=&quot;sigm&quot;, learningrate=0.8, momentum=0.5, learningrate_scale=1, output=&quot;sigm&quot;, numepochs=3, batchsize=100, hidden_dropout=0, visible_dropout=0, cd=1)</code></pre>
<p>Similarly, it is possible to initialize weights from stacked autoencoders. Instead of the parameter <code>output</code>, this example uses <code>sae_output</code>, though it works the same as before.</p>
<pre><code>sae.dnn.train(x, y, hidden=c(1), activationfun=&quot;sigm&quot;, learningrate=0.8, momentum=0.5, learningrate_scale=1, output=&quot;sigm&quot;, sae_output=&quot;linear&quot;, numepochs=3, batchsize=100, hidden_dropout=0, visible_dropout=0)</code></pre>
<p>Finally, we can use a trained network to predict results via <code>nn.predict()</code>. Subsequently, we can transform the predictions with the help of <code>nn.test()</code> into an error rate. The first call requires a neural network and corresponding observations as inputs. The second call additionally needs the correct labels and a threshold when making predictions (default is 0.5).</p>
<pre><code>predictions = nn.predict(nn, test.x) error_rate = nn.test(nn, test.x, test.y, t=0.5)</code></pre>
<p>Altogether, deepnet represents a lightweight package with a restricted set of parameters; however, it offers variety of architectures.</p>
</div>
<div>
<h3><strong>Package “H2O”</strong></h3>
<p>H2O is an open-source software platform with the ability to exploit distributed computer systems <span>(H2O 2015)</span>. Its core is coded in Java and requires the latest version of JVM and JDK, which can be found at <a target="_blank" rel="nofollow" href="https://www.java.com/en/download/">https://www.java.com/en/download/</a>. The package provides interfaces for many languages and was originally designed to serve as a cloud-based platform <span>(Candel et al. 2015)</span>. Accordingly, one starts H2O by calling <code>h2o.init()</code>:</p>
<pre><code>h2o.init(nthreads = -1)</code></pre>
<p>The parameter <code>nthreads</code> specifies how many cores will be used for computation. A value -1 means that H2O will try to use all available cores on the system, though the default is 2. This routine can also work with parameters <code>ip</code> and <code>port</code> in case H2O is installed on a different machine. By default, it uses the ip address 127.0.0.1 together with port 54321. Thus, it is possible to locate the address ‘localhost:54321’ in the browser in order to access a web-based interface. Once your work with the current H2O instance is finished, you need to disconnect via:</p>
<pre><code>h2o.shutdown()</code></pre>
<p><strong>Sample call:</strong></p>
<p>All training operations are performed by <code>h2o.deeplearning()</code> as follows:</p>
<pre><code>model &lt;- h2o.deeplearning(   x=x,   y=y,   training_frame=train,   validation_frame=test,   distribution=&quot;multinomial&quot;,   activation=&quot;RectifierWithDropout&quot;,   hidden=c(32,32,32),   input_dropout_ratio=0.2,   sparse=TRUE,   l1=1e-5,   epochs=100)</code></pre>
<p>The interface for passing data in H2O is a slightly different from other packages: <code>x</code> is a vector containing names of the columns with training data and <code>y</code> is the name of the variable with all the names. The next two parameters, <code>training_frame</code> and <code>validation_frame</code>, are H2O frame objects. They can be created by calling <code>h2o.uploadFile()</code>, which takes a directory path as an argument and loads a csv file into the environment. The use of a specific data class is motivated by the distributed environment, since the data should be available across the whole cluster. The parameter <code>distribution</code> is a string and can take the values <code>‘bernoulli’</code>, <code>‘multinomial’</code>, <code>‘poisson’</code>, <code>‘gamma’</code>, <code>‘tweedie’</code>, <code>‘laplace’</code>, <code>‘huber’</code> or <code>‘gaussian’</code>, while <code>‘AUTO’</code> automatically picks a parameter based on the data. The following parameter specifies the <code>activation</code> function (possible values are <code>‘Tanh’</code>, <code>‘TanhWithDropout’</code>, <code>‘Rectifier’</code>, <code>‘RectifierWithDropout’</code>, <code>‘Maxout’</code> or <code>‘MaxoutWithDropout’</code>). The parameter <code>sparse</code> is a boolean value denoting a high degree of zeros, which allows H2= to handle it more efficiently. The remaining parameters are intuitive and do not differ much from other packages. There are, however, many more available for fine-tuning, but it will probably not be necessary to change them since they come with recommended, pre-defined values.</p>
<p>Finally, we can make predictions using <code>h2o.predict()</code> with the following signature:</p>
<pre><code>predictions &lt;- h2o.predict(model, newdata=test_data)</code></pre>
<p>Another powerful tool that H2O offers is the grid search for optimizing the hyperparameters. It is possible to specify sets of values for each parameter and then find the best combination via <code>h2o.grid()</code>.</p>
<p><strong>Hyperparameter optimization</strong></p>
<pre><code>hidden_par &lt;- list(c(50,20,50), c(32,32,32)) l1_par &lt;- c(1e-3,1e-8) hyperp &lt;- list(hidden=hidden_par, l1=l1_par) model_grid &lt;- h2o.grid(&quot;deeplearning&quot;,                        hyper_params=hyperp,                        x=x,                        y=y,                        distribution=&quot;multinomial&quot;,                        training_frame=train,                        validation_frame=test)</code></pre>
<p>The H2= package will train four different models with two architectures and different L1-regularization weights. Therefore, it is possible to easily try a number of combinations of hyperparameters and see which one performs better:</p>
<pre><code>for (model_id in model_grid@model_ids) {     model &lt;- h2o.getModel(model_id)     mse &lt;- h2o.mse(model, valid=TRUE)     print(sprintf(&quot;MSE on the test set %f&quot;, mse)) }</code></pre>
<p><strong>Deep autoencoders</strong></p>
<p>H2O can also exploit deep autoencoders. To train such a model, the same function <code>h2o.deeplearning()</code> is used but the set of parameters is slightly different</p>
<pre><code>anomaly_model &lt;- h2o.deeplearning(   x = names(train),   training_frame = train,   activation = &quot;Tanh&quot;,   autoencoder = TRUE,   hidden = c(50,20,50),   sparse = TRUE,   l1 = 1e-4,   epochs = 100)</code></pre>
<p>Here, we use only the training data, without the test set and labels. The fact that we need a deep autoencoder instead of a feed-forward Network is specified by the <code>autoencoder</code> parameter. As before, we can choose how many hidden units should be in different layers. If we use one integer value, we will get a naive autoencoder.</p>
<p>After training, we can study the reconstruction error. We compute it by the specific <code>h2o.anomaly()</code> function.</p>
<pre><code># Compute reconstruction error (MSE between output and input layers) recon_error &lt;- h2o.anomaly(anomaly_model, test) # Convert reconstruction error data into R data frame recon_error &lt;- as.data.frame(recon_error)</code></pre>
<p>Overall, H2O is a highly user-friendly package that can be used to train feed-forward networks or deep autoencoders. It supports distributed computations and provides a web interface.</p>
</div>
<div>
<h3><strong>Package “deepr”</strong></h3>
<p>The package deepr <span>(deepr 2015)</span> doesn’t implement any deep learning algorithms itself but forwards its tasks to H20. The package was originally designed at a time when the H2O package was not yet available on CRAN. As this is no longer the case, we will exclude it from our comparison. We also note that its function <code>train_rbm()</code> uses the deepnet implementation of <code>rbm</code> to train a model with some additional output.</p>
</div>
</div>
<div>
<h2>Comparison of Packages</h2>
<p>This section compares the aforementioned packages across different metrics. Among these are ease-of-use, flexibility, ease-of-installation, support of parallel computations and assistance in choosing hyperparameters. In addition, we measure the performance across three common datasets ‘Iris’, ‘MNIST’ and ‘Forest Cover Type’. We hope that our comparison aids practitioners and researchers in choosing their preferred package for deep learning.</p>
<div>
<h4>Installation</h4>
<p>Installing packages that are available via CRAN is usually very simple and smooth. However, some packages depend on third party libraries. For example, H2O requires the latest version of Java, as well as Java Development Kit. The darch and MXNetR packages allow the use of GPU. For that purpose, darch depends on R package gputools, which is only supported on Linux and MacOS systems. MXNetR is by default shipped without GPU support due to its dependence on cuDNN, which cannot be included in the package because of licensing restrictions. Thus, the GPU version of MXNetR requires Rtools and a modern compiler with C++11 support to compile MXNet from source with CUDA SDK and cuDNN.</p>
</div>
<div>
<h4>Flexibility</h4>
<p>With respect to flexibility, MXNetR is most likely at the top of the list. It allows one to experiment with different architectures due to its layer-wise approach of defining the network, not to mention the rich variety of parameters. In our opinion, we think that both H2O and darch score second place. H20 predominantly addresses feed-forward networks and deep autoencoders, while darch focuses on restricted Boltzmann machines and deep belief networks. Both packages offer a broad range of tuning parameters. Last but not least, deepnet is a rather lightweight package but it might be beneficial when one wants to play around with different architectures. However, we do not recommend it for day-to-day use with huge datasets as its current version lacks GPU support and the relatively small set of parameters does not allow fine-tuning to the fullest.</p>
</div>
<div>
<h4>Ease-of-use</h4>
<p>H2O and MXNetR stand out for their speed and ease of use. MXNetR requires little to no preparation of data to start training and H2O offers a very intuitive wrapper by using the <code>as.h2o()</code> function, which converts data to the <code>H2OFrame</code> object. Both packages provide additional tools to examine models. deepnet takes labels in the form of one-hot encoding matrix. This usually requires some pre-processing since most of the datasets have their classes in a vector format. However it does not report very detailed information regarding the progress during training. The package also lacks additional tools for examining models. darch, on the other hand, has a very nice and verbose output.</p>
<p>Overall, we see H2O or MXNetR as the winners in this category, since both are fast and provide feedback during training. This allows one to quickly adjust parameters and improve the predictive performance.</p>
</div>
<div>
<h4>Parallelization</h4>
<p>Deep learning is common when dealing with massive datasets. As such, it can be of tremendous help when the packages allow for some degree of parallelization. Table 2 compares the support of parallelization. It shows only explicitly stated information from the documentation.</p>
<table>
<caption>
<p>Table 2. Comparison of parallelization.</p>
</caption>
<thead>
<tr>
<th align="left">Package</th>
<th align="center">Multiple CPU</th>
<th align="center">[Multiple] GPU</th>
<th align="center">Cluster</th>
<th align="left">Platforms</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left">MXNetR</td>
<td align="center">X</td>
<td align="center">X</td>
<td align="center"></td>
<td align="left">Linux\MacOS\Windows</td>
</tr>
<tr>
<td align="left">darch</td>
<td align="center"></td>
<td align="center">X</td>
<td align="center"></td>
<td align="left">Linux\MaxOS</td>
</tr>
<tr>
<td align="left">H20</td>
<td align="center">X</td>
<td align="center"></td>
<td align="center">X</td>
<td align="left">Linux\MacOS\Windows</td>
</tr>
<tr>
<td align="left">deepnet</td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="left">No information</td>
</tr>
</tbody>
</table>
</div>
<div>
<h4>Choice of parameters</h4>
<p>Another crucial aspect is the choice of hyperparameters. The H2O package uses a fully-automated per-neuron adaptive learning rate for fast convergence. It also has an option to use n-folds cross validation and offers the function <code>h2o.grid()</code> for grid search in order to optimize hyperparameters and model selection.</p>
<p>MXNetR displays the training accuracy after each iteration. darch shows the error after each epoch. Both allow for manually experimenting with different hyperparameters without waiting for the convergence, since the training phase can be terminated earlier in case the accuracy doesn’t improve. In contrast, deepnet doesn’t display any information until training is completed, which makes tweaking the hyperparameters very challenging.</p>
</div>
<div>
<h4>Performance and runtime</h4>
<p>We prepared a very simple comparison of performance in order to provide our readers with information on the efficiency. All subsequent measurements were made on a system with CPU Intel Core i7 and GPU NVidia GeForce 750M, Windows OS. The comparison is carried out on three datasets: ‘MNIST’ <span>(LeCun et al. 2012)</span>, ‘Iris’ <span>(Fisher 1936)</span> and ‘Forest Cover Type’ <span>(Blackard and Dean 1998)</span>. Details are provided in the appendix.</p>
<p>As a baseline, we use the random forest algorithm as implemented in the H2O package. The random forest is an ensemble learning method that works by constructing multiple decision trees <span>(Wikipedia 2016b)</span>. Interestingly, it has proved its ability to achieve a high performance while working out-of-the-box without parameter tuning to a large extent.</p>
<p><strong>Results</strong></p>
<p>The results of the measurements are presented in Table 3 and also visualized in Figures 2, 3, and 4 for the ‘MNIST’, ‘Iris’ and ‘Forest Cover Type’ datasets, respectively.</p>
<ul>
<li><strong>‘MNIST’ dataset.</strong> According to Table 3 and Figure 2, MXNetR and H2O achieve a superior trade-off between runtime and predictive performance on the ‘MNIST’ dataset. darch and deepnet take a relatively long time to train the networks while simultaneously achieving a lower accuracy.</li>
<li><strong>‘Iris’ dataset.</strong> Here, we see again that MXNetR and H2O perform best. As can be seen from Figure 3, deepnet has the lowest accuracy, probably because it is such a tiny dataset where the pre-training is misleading. Because of this, darch 100 and darch 500/300 were trained through backpropagation, omitting a pre-training phase. This is marked by the * symbol in the table.</li>
<li><strong>‘Forest Cover Type’ dataset.</strong> H2O and MXNetR show an accuracy of around 67%, but this is still better that the remaining packages. We note that the training of darch 100 and darch 500/300 didn’t converge, and the models have thus been excluded from this comparison.</li>
</ul>
<p>We hope that even this simple performance comparison can provide valuable insights for practitioners when choosing their preferred R package.</p>
<p><em>Note:</em> It can be seen from Figures 3 and 4 that the random forest can perform better than the deep learning packages. There are several valid reasons for this. First, the datasets are too small as Deep Learning usually requires big data or the use of data augmentation to function properly. Second, the data in these datasets consists of hand-made features, which negates the advantage of deep architectures to learn those features from raw data, and, therefore, traditional methods might be sufficient. Finally, we choose very similar (and probably not the most efficient) architectures in order to compare the different implementations..</p>

<table>
<caption>
<p>Table 3. Comparison of accuracy and runtime across different deep learning packages in R.<br>
* Models that were trained with backpropagation only (no pre-training).</p>
</caption>
<tbody>
<tr>
<th rowspan="2">Model/Dataset</th>
<th colspan="2">MNIST</th>
<th colspan="2">Iris</th>
<th colspan="2">Forest Cover Type</th>
</tr>
<tr>
<td>Accuracy (%)</td>
<td>Runtime (sec)</td>
<td>Accuracy (%)</td>
<td>Runtime (sec)</td>
<td>Accuracy (%)</td>
<td>Runtime (sec)</td>
</tr>
<tr>
<td>MXNetR (CPU)</td>
<td>98.33</td>
<td>147.78</td>
<td>83.04</td>
<td>1.46</td>
<td>66.80</td>
<td>30.24</td>
</tr>
<tr>
<td>MXNetR (GPU)</td>
<td>98.27</td>
<td>336.94</td>
<td>84.77</td>
<td>3.09</td>
<td>67.75</td>
<td>80.89</td>
</tr>
<tr>
<td>darch 100</td>
<td>92.09</td>
<td>1368.31</td>
<td>69.12 *</td>
<td>1.71</td>
<td>–</td>
<td>–</td>
</tr>
<tr>
<td>darch 500/300</td>
<td>95.88</td>
<td>4706.23</td>
<td>54.78 *</td>
<td>2.10</td>
<td>–</td>
<td>–</td>
</tr>
<tr>
<td>deepnet DBN</td>
<td>97.85</td>
<td>6775.40</td>
<td>30.43</td>
<td>0.89</td>
<td>14.06</td>
<td>67.97</td>
</tr>
<tr>
<td>deepnet DNN</td>
<td>97.05</td>
<td>2183.92</td>
<td>78.26</td>
<td>0.42</td>
<td>26.01</td>
<td>25.67</td>
</tr>
<tr>
<td>H2O</td>
<td>98.08</td>
<td>543.14</td>
<td>89.56</td>
<td>0.53</td>
<td>67.36</td>
<td>5.78</td>
</tr>
<tr>
<td>Random Forest</td>
<td>96.77</td>
<td>125.28</td>
<td>91.30</td>
<td>2.89</td>
<td>86.25</td>
<td>9.41</td>
</tr>
</tbody>
</table>
<div>
<p><img sizes="(max-width: 506px) 85vw, 506px" alt="" class="wp-image-26" src="https://i1.wp.com/www.rblog.uni-freiburg.de/wp-content/uploads/2016/11/MNIST.jpg?fit=450%2C600" data-recalc-dims="1"></p>
<p>Figure 2. Comparison of runtime and accuracy for the ‘MNIST’ dataset.</p>
</div>
<div>
<p><img sizes="(max-width: 506px) 85vw, 506px" alt="" class="wp-image-24" src="https://i2.wp.com/www.rblog.uni-freiburg.de/wp-content/uploads/2016/11/Iris.jpg?fit=450%2C600" data-recalc-dims="1"></p>
<p>Figure 3. Comparison of runtime and accuracy for the ‘Iris’ dataset.</p>
</div>
<div>
<p><img sizes="(max-width: 506px) 85vw, 506px" alt="" class="wp-image-25" src="https://i1.wp.com/www.rblog.uni-freiburg.de/wp-content/uploads/2016/11/ForestCoverType.jpg?fit=450%2C600" data-recalc-dims="1"></p>
<p>Figure 4. Comparison of runtime and accuracy for the ‘Forest Cover Type’ dataset.</p>
</div>
</div>
</div>
<div>
<h2>Conclusion</h2>
<p>As part of this article, we have compared five different packages in R for the purpose of deep learning: (1) the current version of deepnet might represent the most differentiated package in terms of available architectures. However, due to its implementation, it might not be the fastest nor the most user-friendly option. Furthermore, it might not offer as many tuning parameters as some of the other packages. (2) H2O and MXNetR, on the contrary, offer a highly user-friendly experience. Both also provide output of additional information, perform training quickly and achieve decent results. H2O might be more suited for cluster environments, where data scientists can use it for data mining and exploration within a straightforward pipeline. When flexibility and prototyping is more of a concern, then MXNetR might be the most suitable choice. It provides an intuitive symbolic tool that is used to build custom network architectures from scratch. Additionally, it is well optimized to run on a personal computer by exploiting multi CPU/GPU capabilities. (3) darch offers a limited but targeted functionality focusing on deep belief networks.</p>
<p>Altogether, we see that R support for deep learning is well on its way. Initially, the offered capabilities of R were lagging behind other programming languages. However, this is no longer the case. With H20 and MXnetR, R users have two powerful tools at their fingertips. In the future, it would be desirable to see further interfaces – e.g. for Caffe or Torch.</p>
</div>
<div>
<h2>Appendix</h2>
<p>‘MNIST’ is a well-known digit recognition dataset. It contains 60,000 training samples and 10,000 test samples with labels and can be downloaded in csv format from <a target="_blank" rel="nofollow" href="http://pjreddie.com/projects/mnist-in-csv/">http://pjreddie.com/projects/mnist-in-csv/</a>. The ‘Forest Cover Type’ dataset originates from a Kaggle challenge and can be found at <a target="_blank" rel="nofollow" href="https://www.kaggle.com/c/forest-cover-type-prediction/data">https://www.kaggle.com/c/forest-cover-type-prediction/data</a>. It contains 15,120 labeled observations that we divide into 70% training set and 30% test set. It has 54 features and 7 output classes of cover type. The ‘Iris’ dataset is also very popular in machine learning. It is a tiny dataset with 3 classes and 150 samples, and we also subdivide it in a 70/30 ratio for training and testing. We immediately observe that practical applications require far larger datasets to unleash the full potential of deep learning. We are aware of this issue but, nevertheless, want to provide a very plain comparison. However, our experiments indicate that not all packages might be suitable for big data and can thus still provide decision support to practitioners.</p>
<p>For the ‘MNIST’ dataset, all networks were designed to have 2 hidden layers with 500 and 300 units, respectively. One exception is darch 100, which has one hidden layer with 100 elements. For other datasets the number of hidden units was reduced by the factor of ten and, hence, architectures have 2 hidden layers with 50 and 30 units, respectively. Where possible, the array batch size was set to 500 elements, momentum to 0.9, learning rate to 0.07 and dropout ratio to 0.2. Number of rounds (in MXNetR) or epochs (in other packages) was set to 50. darch architectures used pre-training with 15 epochs and batch size 100.</p>
<p>The ‘Iris’ dataset is tiny compared to the others. It has only 150 samples that were randomly shuffled and divided for training and test sets. Therefore, all numbers in tables referring to it were averaged across 5 runs. The batch size parameter was reduced to 5 and the learning rate to 0.007.</p>
<p>The third dataset is the ‘Forest Cover Type’, which has 15,120 samples. The architecture of the networks was the same as for the ‘Iris’ dataset. As this dataset is more challenging, the number of epochs was increased from 50 to 100.</p>
<div>
<h1>References</h1>
<p>Blackard, J. A., and Dean, D. J. 1998. “Comparative accuracies of neural networks and discriminant analysis in predicting forest cover types from cartographic variables,” in <em>Proc. second southern forestry gIS conf</em>, pp. 189–199.</p>
<p>Candel, A., Parmar, V., LeDell, E., and Arora, A. 2015. “Deep learning with h2O,”</p>
<p>darch. 2015. “Package darch,” (available at <a target="_blank" rel="nofollow" href="https://cran.r-project.org/web/packages/darch/darch.pdf">https://cran.r-project.org/web/packages/darch/darch.pdf</a>).</p>
<p>deepnet. 2015. “Package deepnet,” (available at <a target="_blank" rel="nofollow" href="https://cran.r-project.org/web/packages/deepnet/deepnet.pdf">https://cran.r-project.org/web/packages/deepnet/deepnet.pdf</a>).</p>
<p>deepr. 2015. “Deepr,” (available at <a target="_blank" rel="nofollow" href="https://github.com/woobe/deepr">https://github.com/woobe/deepr</a>; retrieved January 9, 2016).</p>
<p>Fisher, R. A. 1936. “The use of multiple measurements in taxonomic problems,” <em>Annals of eugenics</em> (7:2), pp. 179–188.</p>
<p>H2O. 2015. “Package h2o,” (available at <a target="_blank" rel="nofollow" href="https://cran.r-project.org/web/packages/h2o/h2o.pdf">https://cran.r-project.org/web/packages/h2o/h2o.pdf</a>).</p>
<p>LeCun, Y. A., Bottou, L., Orr, G. B., and Müller, K.-R. 2012. “Efficient backprop,” in <em>Neural networks: Tricks of the trade</em>, Springer, pp. 9–48.</p>
<p>MXNetR. 2016a. “MXNet r package: Mxnet 0.5.0 documentation,” (available at <a target="_blank" rel="nofollow" href="https://mxnet.readthedocs.org/en/latest/R-package/index.html#tutorials">https://mxnet.readthedocs.org/en/latest/R-package/index.html#tutorials</a>; retrieved January 9, 2016).</p>
<p>MXNetR. 2016b. “Installation guide: Mxnet 0.5.0 documentation,” (available at <a target="_blank" rel="nofollow" href="https://mxnet.readthedocs.org/en/latest/build.html">https://mxnet.readthedocs.org/en/latest/build.html</a>; retrieved January 9, 2016).</p>
<p>Nair, V., and Hinton, G. E. 2010. “Rectified linear units improve restricted boltzmann machines,” in <em>Proceedings of the 27th international conference on machine learning (iCML-10)</em>, pp. 807–814.</p>
<p>Srivastava, N., Hinton, G., Krizhevsky, A., Sutskever, I., and Salakhutdinov, R. 2014. “Dropout: A simple way to prevent neural networks from overfitting,” <em>Journal of Machine Learning Research</em> (15:1), pp. 1929–1958.</p>
<p>Wikipedia. 2016a. “Wikipedia: Deep learning,” (available at <a target="_blank" rel="nofollow" href="https://en.wikipedia.org/wiki/Deep_learning">https://en.wikipedia.org/wiki/Deep_learning</a>; retrieved March 17, 2016).</p>
<p>Wikipedia. 2016b. “Wikipedia: Random forest,” (available at <a target="_blank" rel="nofollow" href="https://en.wikipedia.org/wiki/Random_forest">https://en.wikipedia.org/wiki/Random_forest</a>; retrieved February 3, 2016).</p>
</div>
</div>
</div>
<p> </p>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://www.rblog.uni-freiburg.de/2017/02/07/deep-learning-in-r/"> R Blog</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/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/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/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/A_3PhK7UrRA"></a></div>