```
library(keras)
library(tensorflow)
<- dataset_mnist()
mnist
$train$x <- (mnist$train$x/255) %>%
mnistarray_reshape(., dim = c(dim(.), 1))
$test$x <- (mnist$test$x/255) %>%
mnistarray_reshape(., dim = c(dim(.), 1))
```

# Deploying a TensorFlow Model to RStudio Connect

In this tutorial you will learn how to deploy a TensorFlow model to RStudio Connect. RStudio Connect uses TensorFlow Serving for performance but makes it much easier for R users to manage their deployment.

## Building the model

The first thing we are going to do is to build our model. We will use the Keras API to build this model.

We will use the MNIST dataset to build our model.

Now, we are going to define our Keras model, it will be a simple convolutional neural network.

```
<- keras_model_sequential() %>%
model layer_conv_2d(filters = 16, kernel_size = c(3,3), activation = "relu") %>%
layer_max_pooling_2d(pool_size = c(2,2)) %>%
layer_conv_2d(filters = 16, kernel_size = c(3,3), activation = "relu") %>%
layer_max_pooling_2d(pool_size = c(2,2)) %>%
layer_flatten() %>%
layer_dense(units = 128, activation = "relu") %>%
layer_dense(units = 10, activation = "softmax")
%>%
model compile(
loss = "sparse_categorical_crossentropy",
optimizer = "adam",
metrics = "accuracy"
)
```

Next, we fit the model using the MNIST dataset:

```
%>%
model fit(
x = mnist$train$x, y = mnist$train$y,
batch_size = 32,
epochs = 5,
validation_sample = 0.2,
verbose = 2
)
```

When we are happy with our model accuracy in the validation dataset we can `evaluate`

the results on the test dataset with:

`%>% evaluate(x = mnist$test$x, y = mnist$test$y, verbose = 0) model `

```
loss accuracy
0.03027044 0.99000001
```

OK, we have 99% accuracy on the test dataset and we want to deploy that model. First, let’s save the model in the `SavedModel`

format using:

`save_model_tf(model, "cnn-mnist")`

With the model built and saved we can now start building our plumber API file.

## Deployiong to RStudio Connect

Once the model is saved to the SavedModel format, the model can be deployed with a single line of code:

`::deployTFModel("cnn-mnist/") rsconnect`

When the deployment is complete you will be redirected to your browser with some instructions on how to call the REST endpoint: