17.1 TensorFlow in R

# example from https://tensorflow.rstudio.com/tensorflow/articles/examples/mnist_softmax.html

library(tensorflow)
# Define hyperparameters -----------

batch_size <- 128
num_classes <- 10
steps <- 1000
# Data Preparation -----------

datasets <- tf$contrib$learn$datasets
mnist <- datasets$mnist$read_data_sets("MNIST-data", one_hot = TRUE)
# Define Model ---------------

# Create the model
x <- tf$placeholder(tf$float32, shape(NULL, 784L))
W <- tf$Variable(tf$zeros(shape(784L, num_classes)))
b <- tf$Variable(tf$zeros(shape(num_classes)))

y <- tf$nn$softmax(tf$matmul(x, W) + b)

# Define loss and optimizer
y_ <- tf$placeholder(tf$float32, shape(NULL, num_classes))
cross_entropy <- tf$reduce_mean(-tf$reduce_sum(y_ * log(y), reduction_indices=1L))
train_step <- tf$train$GradientDescentOptimizer(0.5)$minimize(cross_entropy)
# Training the model --------

# Create session and initialize  variables
sess <- tf$Session()
sess$run(tf$global_variables_initializer())

# Train
for (i in 1:steps) {
  batches <- mnist$train$next_batch(batch_size)
  batch_xs <- batches[[1]]
  batch_ys <- batches[[2]]
  sess$run(train_step,
           feed_dict = dict(x = batch_xs, y_ = batch_ys))
}
# Evaluate the model --------

correct_prediction <- tf$equal(tf$argmax(y, 1L), tf$argmax(y_, 1L))
accuracy <- tf$reduce_mean(tf$cast(correct_prediction, tf$float32))
score <-sess$run(accuracy,
         feed_dict = dict(x = mnist$test$images, y_ = mnist$test$labels))

cat('Test accuracy:', score, '\n')
Test accuracy: 0.9185 

results matching ""

    No results matching ""