<p>We are excited to announce that the <a rel="nofollow" href="https://keras.rstudio.com/" target="_blank">keras package</a> is now available on CRAN. The package provides an R interface to <a rel="nofollow" href="https://keras.io/" target="_blank">Keras</a>, a high-level neural networks API developed with a focus on enabling fast experimentation. Keras has the following key features:</p>
<ul>
<li>
<p>Allows the same code to run on CPU or on GPU, seamlessly.</p>
</li>
<li>
<p>User-friendly API which makes it easy to quickly prototype deep learning models.</p>
</li>
<li>
<p>Built-in support for convolutional networks (for computer vision), recurrent networks (for sequence processing), and any combination of both.</p>
</li>
<li>
<p>Supports arbitrary network architectures: multi-input or multi-output models, layer sharing, model sharing, etc. This means that Keras is appropriate for building essentially any deep learning model, from a memory network to a neural Turing machine.</p>
</li>
<li>
<p>Is capable of running on top of multiple back-ends including <a rel="nofollow" href="https://github.com/tensorflow/tensorflow" target="_blank">TensorFlow</a>, <a rel="nofollow" href="https://github.com/Microsoft/cntk" target="_blank">CNTK</a>, or <a rel="nofollow" href="https://github.com/Theano/Theano" target="_blank">Theano</a>.</p>
</li>
</ul>
<p>If you are already familiar with Keras and want to jump right in, check out <a rel="nofollow" href="https://keras.rstudio.com/" target="_blank">https://keras.rstudio.com</a> which has everything you need to get started including over 20 complete examples to learn from.</p>
<p>To learn a bit more about Keras and why we’re so excited to announce the Keras interface for R, read on!</p>
<h2>Keras and Deep Learning</h2>
<p>Interest in deep learning has been accelerating rapidly over the past few years, and several deep learning frameworks have emerged over the same time frame. Of all the available frameworks, Keras has stood out for its productivity, flexibility and user-friendly API. At the same time, TensorFlow has emerged as a next-generation machine learning platform that is both extremely flexible and well-suited to production deployment.</p>
<p>Not surprisingly, Keras and TensorFlow have of late been pulling away from other deep learning frameworks:</p>
<p>
<blockquote class="twitter-tweet" data-lang="en">
<p lang="en" dir="ltr">Google web search interest around deep learning frameworks over time. If you remember Q4 2015 and Q1-2 2016 as confusing, you weren't alone. <a rel="nofollow" href="https://t.co/1f1VQVGr8n" target="_blank">pic.twitter.com/1f1VQVGr8n</a></p>
<p>— François Chollet (@fchollet) <a rel="nofollow" href="https://twitter.com/fchollet/status/871089784898310144" target="_blank">June 3, 2017</a></p></blockquote>
<p></p>
<p>The good news about Keras and TensorFlow is that you don’t need to choose between them! The default backend for Keras is TensorFlow and Keras can be <a rel="nofollow" href="https://blog.keras.io/keras-as-a-simplified-interface-to-tensorflow-tutorial.html" target="_blank">integrated seamlessly</a> with TensorFlow workflows. There is also a pure-TensorFlow implementation of Keras with <a rel="nofollow" href="https://www.youtube.com/watch?v=UeheTiBJ0Io&t=7s&index=8&list=PLOU2XLYxmsIKGc_NBoIhTn2Qhraji53cv" target="_blank">deeper integration</a> on the roadmap for later this year.</p>
<p>Keras and TensorFlow are the state of the art in deep learning tools and with the keras package you can now access both with a fluent R interface.</p>
<h2>Getting Started</h2>
<h3>Installation</h3>
<p>To begin, install the keras R package from CRAN as follows:</p>
<pre><code>install.packages(&quot;keras&quot;)
</code></pre>
<p>The Keras R interface uses the <a rel="nofollow" href="https://www.tensorflow.org/" target="_blank">TensorFlow</a> backend engine by default. To install both the core Keras library as well as the TensorFlow backend use the <code>install_keras()</code> function:</p>
<pre><code>library(keras)
install_keras()
</code></pre>
<p>This will provide you with default CPU-based installations of Keras and TensorFlow. If you want a more customized installation, e.g. if you want to take advantage of NVIDIA GPUs, see the documentation for <a rel="nofollow" href="https://keras.rstudio.com/reference/install_keras.html" target="_blank"><code>install_keras()</code></a>.</p>
<h3>MNIST Example</h3>
<p>We can learn the basics of Keras by walking through a simple example: recognizing handwritten digits from the <a rel="nofollow" href="https://en.wikipedia.org/wiki/MNIST_database" target="_blank">MNIST</a> dataset. MNIST consists of 28 x 28 grayscale images of handwritten digits like these:</p>
<p><img src="https://i2.wp.com/www.tensorflow.org/images/MNIST.png?w=456&ssl=1" data-recalc-dims="1"></p>
<p>The dataset also includes labels for each image, telling us which digit it is. For example, the labels for the above images are 5, 0, 4, and 1.</p>
<h4>Preparing the Data</h4>
<p>The MNIST dataset is included with Keras and can be accessed using the <code>dataset_mnist()</code> function. Here we load the dataset then create variables for our test and training data:</p>
<pre><code>library(keras)
mnist &lt;- dataset_mnist()
x_train &lt;- mnist$train$x
y_train &lt;- mnist$train$y
x_test &lt;- mnist$test$x
y_test &lt;- mnist$test$y
</code></pre>
<p>The <code>x</code> data is a 3-d array <code>(images,width,height)</code> of grayscale values. To prepare the data for training we convert the 3-d arrays into matrices by reshaping width and height into a single dimension (28×28 images are flattened into length 784 vectors). Then, we convert the grayscale values from integers ranging between 0 to 255 into floating point values ranging between 0 and 1:</p>
<pre><code># reshape
dim(x_train) &lt;- c(nrow(x_train), 784)
dim(x_test) &lt;- c(nrow(x_test), 784)
# rescale
x_train &lt;- x_train / 255
x_test &lt;- x_test / 255
</code></pre>
<p>The <code>y</code> data is an integer vector with values ranging from 0 to 9. To prepare this data for training we <a rel="nofollow" href="https://www.quora.com/What-is-one-hot-encoding-and-when-is-it-used-in-data-science" target="_blank">one-hot encode</a> the vectors into binary class matrices using the Keras <code>to_categorical()</code> function:</p>
<pre><code>y_train &lt;- to_categorical(y_train, 10)
y_test &lt;- to_categorical(y_test, 10)
</code></pre>
<h4>Defining the Model</h4>
<p>The core data structure of Keras is a model, a way to organize layers. The simplest type of model is the <a rel="nofollow" href="https://keras.rstudio.com/articles/sequential_model.html" target="_blank">sequential model</a>, a linear stack of layers.</p>
<p>We begin by creating a sequential model and then adding layers using the pipe (<code>%>%</code>) operator:</p>
<pre><code>model &lt;- keras_model_sequential() 
model %>% 
  layer_dense(units = 256, activation = &quot;relu&quot;, input_shape = c(784)) %>% 
  layer_dropout(rate = 0.4) %>% 
  layer_dense(units = 128, activation = &quot;relu&quot;) %>%
  layer_dropout(rate = 0.3) %>%
  layer_dense(units = 10, activation = &quot;softmax&quot;)
</code></pre>
<p>The <code>input_shape</code> argument to the first layer specifies the shape of the input data (a length 784 numeric vector representing a grayscale image). The final layer outputs a length 10 numeric vector (probabilities for each digit) using a <a rel="nofollow" href="https://en.wikipedia.org/wiki/Softmax_function" target="_blank">softmax activation function</a>.</p>
<p>Use the <code>summary()</code> function to print the details of the model:</p>
<pre><code>summary(model)
</code></pre>
<pre><code>Model
________________________________________________________________________________
Layer (type)                        Output Shape                    Param #     
================================================================================
dense_1 (Dense)                     (None, 256)                     200960      
________________________________________________________________________________
dropout_1 (Dropout)                 (None, 256)                     0           
________________________________________________________________________________
dense_2 (Dense)                     (None, 128)                     32896       
________________________________________________________________________________
dropout_2 (Dropout)                 (None, 128)                     0           
________________________________________________________________________________
dense_3 (Dense)                     (None, 10)                      1290        
================================================================================
Total params: 235,146
Trainable params: 235,146
Non-trainable params: 0
________________________________________________________________________________</code></pre>
<p>Next, compile the model with appropriate loss function, optimizer, and metrics:</p>
<pre><code>model %>% compile(
  loss = &quot;categorical_crossentropy&quot;,
  optimizer = optimizer_rmsprop(),
  metrics = c(&quot;accuracy&quot;)
)
</code></pre>
<h4>Training and Evaluation</h4>
<p>Use the <code>fit()</code> function to train the model for 30 epochs using batches of 128 images:</p>
<pre><code>history &lt;- model %>% fit(
  x_train, y_train, 
  epochs = 30, batch_size = 128, 
  validation_split = 0.2
)
</code></pre>
<p>The <code>history</code> object returned by <code>fit()</code> includes loss and accuracy metrics which we can plot:</p>
<pre><code>plot(history)
</code></pre>
<p><img alt="" src="https://i1.wp.com/keras.rstudio.com/images/training_history_ggplot2.png?w=456&ssl=1" data-recalc-dims="1"></p>
<p>Evaluate the model’s performance on the test data:</p>
<pre><code>model %>% evaluate(x_test, y_test,verbose = 0)
</code></pre>
<pre><code>$loss
[1] 0.1149

$acc
[1] 0.9807
</code></pre>
<p>Generate predictions on new data:</p>
<pre><code>model %>% predict_classes(x_test)
</code></pre>
<pre><code>  [1] 7 2 1 0 4 1 4 9 5 9 0 6 9 0 1 5 9 7 3 4 9 6 6 5 4 0 7 4 0 1 3 1 3 4 7 2 7 1 2
 [40] 1 1 7 4 2 3 5 1 2 4 4 6 3 5 5 6 0 4 1 9 5 7 8 9 3 7 4 6 4 3 0 7 0 2 9 1 7 3 2
 [79] 9 7 7 6 2 7 8 4 7 3 6 1 3 6 9 3 1 4 1 7 6 9
 [ reached getOption(&quot;max.print&quot;) -- omitted 9900 entries ]
</code></pre>
<p>Keras provides a vocabulary for building deep learning models that is simple, elegant, and intuitive. Building a question answering system, an image classification model, a neural Turing machine, or any other model is just as straightforward.</p>
<p>The <a rel="nofollow" href="https://keras.rstudio.com/articles/sequential_model.html" target="_blank">Guide to the Sequential Model</a> article describes the basics of Keras sequential models in more depth.</p>
<h2>Examples</h2>
<p>Over 20 complete examples are available (special thanks to <a rel="nofollow" href="https://github.com/dfalbel" target="_blank">@dfalbel</a> for his work on these!). The examples cover image classification, text generation with stacked LSTMs, question-answering with memory networks, transfer learning, variational encoding, and more.</p>
<table>
<thead>
<tr>
<th>Example</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/addition_rnn.html" target="_blank">addition_rnn</a></td>
<td>Implementation of sequence to sequence learning for performing addition of two numbers (as strings).</td>
</tr>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/babi_memnn.html" target="_blank">babi_memnn</a></td>
<td>Trains a memory network on the bAbI dataset for reading comprehension.</td>
</tr>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/babi_rnn.html" target="_blank">babi_rnn</a></td>
<td>Trains a two-branch recurrent network on the bAbI dataset for reading comprehension.</td>
</tr>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/cifar10_cnn.html" target="_blank">cifar10_cnn</a></td>
<td>Trains a simple deep CNN on the CIFAR10 small images dataset.</td>
</tr>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/conv_lstm.html" target="_blank">conv_lstm</a></td>
<td>Demonstrates the use of a convolutional LSTM network.</td>
</tr>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/deep_dream.html" target="_blank">deep_dream</a></td>
<td>Deep Dreams in Keras.</td>
</tr>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/imdb_bidirectional_lstm.html" target="_blank">imdb_bidirectional_lstm</a></td>
<td>Trains a Bidirectional LSTM on the IMDB sentiment classification task.</td>
</tr>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/imdb_cnn.html" target="_blank">imdb_cnn</a></td>
<td>Demonstrates the use of Convolution1D for text classification.</td>
</tr>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/imdb_cnn_lstm.html" target="_blank">imdb_cnn_lstm</a></td>
<td>Trains a convolutional stack followed by a recurrent stack network on the IMDB sentiment classification task.</td>
</tr>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/imdb_fasttext.html" target="_blank">imdb_fasttext</a></td>
<td>Trains a FastText model on the IMDB sentiment classification task.</td>
</tr>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/imdb_lstm.html" target="_blank">imdb_lstm</a></td>
<td>Trains a LSTM on the IMDB sentiment classification task.</td>
</tr>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/lstm_text_generation.html" target="_blank">lstm_text_generation</a></td>
<td>Generates text from Nietzsche’s writings.</td>
</tr>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/mnist_acgan.html" target="_blank">mnist_acgan</a></td>
<td>Implementation of AC-GAN (Auxiliary Classifier GAN ) on the MNIST dataset</td>
</tr>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/mnist_antirectifier.html" target="_blank">mnist_antirectifier</a></td>
<td>Demonstrates how to write custom layers for Keras</td>
</tr>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/mnist_cnn.html" target="_blank">mnist_cnn</a></td>
<td>Trains a simple convnet on the MNIST dataset.</td>
</tr>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/mnist_irnn.html" target="_blank">mnist_irnn</a></td>
<td>Reproduction of the IRNN experiment with pixel-by-pixel sequential MNIST in “A Simple Way to Initialize Recurrent Networks of Rectified Linear Units” by Le et al.</td>
</tr>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/mnist_mlp.html" target="_blank">mnist_mlp</a></td>
<td>Trains a simple deep multi-layer perceptron on the MNIST dataset.</td>
</tr>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/mnist_hierarchical_rnn.html" target="_blank">mnist_hierarchical_rnn</a></td>
<td>Trains a Hierarchical RNN (HRNN) to classify MNIST digits.</td>
</tr>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/mnist_transfer_cnn.html" target="_blank">mnist_transfer_cnn</a></td>
<td>Transfer learning toy example.</td>
</tr>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/neural_style_transfer.html" target="_blank">neural_style_transfer</a></td>
<td>Neural style transfer (generating an image with the same “content” as a base image, but with the “style” of a different picture).</td>
</tr>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/reuters_mlp.html" target="_blank">reuters_mlp</a></td>
<td>Trains and evaluates a simple MLP on the Reuters newswire topic classification task.</td>
</tr>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/stateful_lstm.html" target="_blank">stateful_lstm</a></td>
<td>Demonstrates how to use stateful RNNs to model long sequences efficiently.</td>
</tr>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/variational_autoencoder.html" target="_blank">variational_autoencoder</a></td>
<td>Demonstrates how to build a variational autoencoder.</td>
</tr>
<tr>
<td><a rel="nofollow" href="https://keras.rstudio.com/articles/examples/variational_autoencoder_deconv.html" target="_blank">variational_autoencoder_deconv</a></td>
<td>Demonstrates how to build a variational autoencoder with Keras using deconvolution layers.</td>
</tr>
</tbody>
</table>
<h2>Learning More</h2>
<p>After you’ve become familiar with the basics, these articles are a good next step:</p>
<ul>
<li>
<p><a rel="nofollow" href="https://keras.rstudio.com/articles/sequential_model.html" target="_blank">Guide to the Sequential Model</a>. The sequential model is a linear stack of layers and is the API most users should start with.</p>
</li>
<li>
<p><a rel="nofollow" href="https://keras.rstudio.com/articles/functional_api.html" target="_blank">Guide to the Functional API</a>. The Keras functional API is the way to go for defining complex models, such as multi-output models, directed acyclic graphs, or models with shared layers.</p>
</li>
<li>
<p><a rel="nofollow" href="https://keras.rstudio.com/articles/training_visualization.html" target="_blank">Training Visualization</a>. There are a wide variety of tools available for visualizing training. These include plotting of training metrics, real time display of metrics within the RStudio IDE, and integration with the TensorBoard visualization tool included with TensorFlow.</p>
</li>
<li>
<p><a rel="nofollow" href="https://keras.rstudio.com/articles/applications.html" target="_blank">Using Pre-Trained Models</a>. Keras includes a number of deep learning models (Xception, VGG16, VGG19, ResNet50, InceptionVV3, and MobileNet) that are made available alongside pre-trained weights. These models can be used for prediction, feature extraction, and fine-tuning.</p>
</li>
<li>
<p><a rel="nofollow" href="https://keras.rstudio.com/articles/faq.html" target="_blank">Frequently Asked Questions</a>. Covers many additional topics including streaming training data, saving models, training on GPUs, and more.</p>
</li>
</ul>
<p>Keras provides a productive, highly flexible framework for developing deep learning models. We can’t wait to see what the R community will do with these tools!</p>

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