<jupyter_start><jupyter_text>Table of Contents  Keras in R<jupyter_code># example from https://keras.rstudio.com/articles/examples/mnist_mlp.html

library(keras)
# Define hyperparameters -----------

batch_size <- 128
num_classes <- 10
epochs <- 30
# Data Preparation -----------

# The data, shuffled and split between train and test sets
c(c(x_train, y_train), c(x_test, y_test)) %<-% dataset_mnist()

x_train <- array_reshape(x_train, c(nrow(x_train), 784))
x_test <- array_reshape(x_test, c(nrow(x_test), 784))

# Transform RGB values into [0,1] range
x_train <- x_train / 255
x_test <- x_test / 255

cat(nrow(x_train), 'train samples\n')
cat(nrow(x_test), 'test samples\n')

# Convert class vectors to binary class matrices
y_train <- to_categorical(y_train, num_classes)
y_test <- to_categorical(y_test, num_classes)
# Define Model ---------------

model <- keras_model_sequential()
model %>% 
  layer_dense(units = 256, activation = 'relu', input_shape = c(784)) %>% 
  layer_dropout(rate = 0.4) %>% 
  layer_dense(units = 128, activation = 'relu') %>%
  layer_dropout(rate = 0.3) %>%
  layer_dense(units = 10, activation = 'softmax')

summary(model)

model %>% compile(
  loss = 'categorical_crossentropy',
  optimizer = optimizer_rmsprop(),
  metrics = c('accuracy')
)
# Training the model --------
history <- model %>% fit(
  x_train, y_train,
  batch_size = batch_size,
  epochs = epochs,
  verbose = 1,
  validation_split = 0.2
)

plot(history)
# Evaluate the model --------

score <- model %>% evaluate(
  x_test, y_test,
  verbose = 0
)

# Output metrics
cat('Test loss:', score[[1]], '\n')
cat('Test accuracy:', score[[2]], '\n')<jupyter_output>Test loss: 0.1128517 
Test accuracy: 0.9816
{'fraction_non_alphanumeric': 0.17146212566059893, 'fraction_numerical': 0.03229594832648268, 'mean_word_length': 4.041420118343195, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 12, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '31062', 'license': 'MIT', 'n_tokens_mistral': 691, 'n_tokens_neox': 615, 'n_words': 148, 'path': 'Chapter17/ch-17c_Keras_in_R.ipynb', 'repo_name': 'vgoklani/Mastering-TensorFlow-1x', 'size': '1703'}