<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/deep-learning-with-r/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://datascienceplus.com/deep-learning-with-r/"> R Programming – DataScience+</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>For R users, there hasn’t been a production grade solution for deep learning (sorry <a rel="nofollow" href="http://mxnet.io/api/r/index.html" target="_blank">MXNET</a>). This post introduces the Keras interface for R and how it can be used to perform image classification. The post ends by providing some code snippets that show Keras is intuitive and powerful.</p>
<h2>Tensorflow</h2>
<p>Last January, <a rel="nofollow" href="https://github.com/rstudio/tensorflow" target="_blank">Tensorflow for R</a> was released, which provided access to the Tensorflow API from R. However, for most R users, the interface was not very R like. </p>
<p>Take a look at this code chunk for training a model:</p>
<pre>
cross_entropy &lt;- tf$reduce_mean(-tf$reduce_sum(y_ * tf$log(y_conv), reduction_indices=1L))
train_step &lt;- tf$train$AdamOptimizer(1e-4)$minimize(cross_entropy)
correct_prediction &lt;- tf$equal(tf$argmax(y_conv, 1L), tf$argmax(y_, 1L))
accuracy &lt;- tf$reduce_mean(tf$cast(correct_prediction, tf$float32))
sess$run(tf$global_variables_initializer())

for (i in 1:20000) {
  batch &lt;- mnist$train$next_batch(50L)
  if (i %% 100 == 0) {
    train_accuracy &lt;- accuracy$eval(feed_dict = dict(
        x = batch[[1]], y_ = batch[[2]], keep_prob = 1.0))
    cat(sprintf(&quot;step %d, training accuracy %g\n&quot;, i, train_accuracy))
  }
  train_step$run(feed_dict = dict(
    x = batch[[1]], y_ = batch[[2]], keep_prob = 0.5))
}

test_accuracy % fit(
        x = train_x, y = train_y,
        epochs=epochs, 
        batch_size=batch_size,
        validation_data=valid)
</pre>
<h2>Image Classification with Keras</h2>
<p>So if you are still with me, let me show you how to build deep learning models using R, Keras, and Tensorflow together. You will find a <a rel="nofollow" href="https://github.com/rajshah4/image_keras/" target="_blank">Github repo</a> that contains the code and data you will need. Included is an <a rel="nofollow" href="http://htmlpreview.github.io/?https://github.com/rajshah4/image_keras/blob/master/Rnotebook.nb.html" target="_blank">R notebook</a> that walks through building an image classifier (telling cat from dog), but can easily be generalized to other images. The walk through includes advanced methods that are commonly used for production deep learning work including:</p>
<ul>
<li>augmenting data</li>
<li>using the bottleneck features of a pre-trained network</li>
<li>fine-tuning the top layers of a pre-trained network</li>
<li>saving weights for your models</li>
</ul>
<h2>Code Snippets of Keras</h2>
<p>The R interface to Keras truly makes it easy to build deep learning models in R. Here are some code snippets to illustrate how intuitive and useful Keras for R is:</p>
<p>To load picture from a folder:</p>
<pre>
train_generator &lt;- flow_images_from_directory(train_directory, generator = image_data_generator(),
  target_size = c(img_width, img_height), color_mode = &quot;rgb&quot;,
  class_mode = &quot;binary&quot;, batch_size = batch_size, shuffle = TRUE,
  seed = 123)
</pre>
<p>To define a simple convolutional neural network:</p>
<pre>
model %
  layer_conv_2d(filter = 32, kernel_size = c(3,3), input_shape = c(img_width, img_height, 3)) %>%
  layer_activation(&quot;relu&quot;) %>%
  layer_max_pooling_2d(pool_size = c(2,2)) %>% 
  
  layer_conv_2d(filter = 32, kernel_size = c(3,3)) %>%
  layer_activation(&quot;relu&quot;) %>%
  layer_max_pooling_2d(pool_size = c(2,2)) %>%
  
  layer_conv_2d(filter = 64, kernel_size = c(3,3)) %>%
  layer_activation(&quot;relu&quot;) %>%
  layer_max_pooling_2d(pool_size = c(2,2)) %>%
  
  layer_flatten() %>%
  layer_dense(64) %>%
  layer_activation(&quot;relu&quot;) %>%
  layer_dropout(0.5) %>%
  layer_dense(1) %>%
  layer_activation(&quot;sigmoid&quot;)
</pre>
<p>To augment data:</p>
<pre>
augment &lt;- image_data_generator(rescale=1./255,
                               shear_range=0.2,
                               zoom_range=0.2,
                               horizontal_flip=TRUE)
</pre>
<p>To load a pretrained network:</p>
<pre>
model_vgg &lt;- application_vgg16(include_top = FALSE, weights = &quot;imagenet&quot;)
</pre>
<p>To save model weights:</p>
<pre>
save_model_weights_hdf5(model_ft, 'finetuning_30epochs_vggR.h5', overwrite = TRUE)
</pre>
<p>I believe the Keras for R interface will make it much easier for R users and the R community to build and refine deep learning models with R. This means you don't have to force everyone to use python to build, refine, and test your models. I really think this will open up deep learning to a wider audience that was a bit apprehensive on using Python. So for now, give it a spin! </p>
<p>Grab my <a rel="nofollow" href="https://github.com/rajshah4/image_keras/" target="_blank">github repo</a>, fire up RStudio (or your IDE of choice), and go build a simple classifier using Keras.</p>
<ul></ul>
<p><strong>
<p>Related Post</p>
<p>
<ol>
<li><a rel="nofollow" href="https://datascienceplus.com/unsupervised-learning-and-text-mining-of-emotion-terms-using-r/" title="Permanent Link toUnsupervised Learning and Text Mining of Emotion Terms Using R" target="_blank">Unsupervised Learning and Text Mining of Emotion Terms Using R</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/using-mca-and-variable-clustering-in-r-for-insights-in-customer-attrition/" title="Permanent Link toUsing MCA and variable clustering in R for insights in customer attrition" target="_blank">Using MCA and variable clustering in R for insights in customer attrition</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/web-scraping-and-applied-clustering-global-happiness-and-social-progress-index/" title="Permanent Link toWeb Scraping and Applied Clustering Global Happiness and Social Progress Index" target="_blank">Web Scraping and Applied Clustering Global Happiness and Social Progress Index</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/key-phrase-extraction-from-tweets/" title="Permanent Link toKey Phrase Extraction from Tweets" target="_blank">Key Phrase Extraction from Tweets</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/financial-time-series-forecasting-an-easy-approach/" title="Permanent Link toFinancial time series forecasting – an easy approach" target="_blank">Financial time series forecasting – an easy approach</a></li>
</ol></strong>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://datascienceplus.com/deep-learning-with-r/"> R Programming – DataScience+</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 rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...

	<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/d4h8Rhyv5UE" height="1"></a></div>