Deep learning

Keras

Atenção Leia antes o notebook "install_tensorflow"! Antes de rodar os comandos abaixo, se estiver usando o Jupyter dentro do Anaconda em sua máquina local, saia do Jupyter, e digite: pip install keras Depois, abra o jupyter novamente e rode os comandos abaixo.


In [1]:
install.packages("keras", repos='http://cran.us.r-project.org')


Updating HTML index of packages in '.Library'
Making 'packages.html' ... done

In [2]:
library(keras)
install_keras()


Using r-tensorflow conda environment for TensorFlow installation
Determining latest release of TensorFlow...done
Installing TensorFlow...

Installation complete.


In [3]:
mnist <- dataset_mnist()
x_train <- mnist$train$x
y_train <- mnist$train$y
x_test <- mnist$test$x
y_test <- mnist$test$y

In [4]:
# reshape
x_train <- array_reshape(x_train, c(nrow(x_train), 784))
x_test <- array_reshape(x_test, c(nrow(x_test), 784))
# rescale
x_train <- x_train / 255
x_test <- x_test / 255

In [5]:
y_train <- to_categorical(y_train, 10)
y_test <- to_categorical(y_test, 10)

In [6]:
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')

In [7]:
summary(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
________________________________________________________________________________

In [8]:
model %>% compile(
  loss = 'categorical_crossentropy',
  optimizer = optimizer_rmsprop(),
  metrics = c('accuracy')
)

In [9]:
history <- model %>% fit(
  x_train, y_train, 
  epochs = 30, batch_size = 128, 
  validation_split = 0.2
)

In [10]:
plot(history)



In [ ]: