17.2 TF Estimator in R
library(tensorflow)
library(tfestimators)
batch_size <- 128
n_classes <- 10
n_steps <- 100
data_dir <- "~/datasets/mnist"
dir.create(data_dir, recursive = TRUE, showWarnings = FALSE)
sources <- list(
train = list(
x = "https://storage.googleapis.com/cvdf-datasets/mnist/train-images-idx3-ubyte.gz",
y = "https://storage.googleapis.com/cvdf-datasets/mnist/train-labels-idx1-ubyte.gz"
),
test = list(
x = "https://storage.googleapis.com/cvdf-datasets/mnist/t10k-images-idx3-ubyte.gz",
y = "https://storage.googleapis.com/cvdf-datasets/mnist/t10k-labels-idx1-ubyte.gz"
)
)
read_idx <- function(file) {
conn <- gzfile(file, open = "rb")
on.exit(close(conn), add = TRUE)
magic <- readBin(conn, what = "raw", n = 4, endian = "big")
ndims <- as.integer(magic[[4]])
dims <- readBin(conn, what = "integer", n = ndims, endian = "big")
data <- readBin(conn, what = "raw", n = prod(dims), endian = "big")
converted <- as.integer(data)
if (length(dims) == 1)
return(converted)
matrix(converted, nrow = dims[1], ncol = prod(dims[-1]), byrow = TRUE)
}
mnist <- rapply(sources, classes = "character", how = "list", function(url) {
target <- file.path(data_dir, basename(url))
if (!file.exists(target))
download.file(url, target)
read_idx(target)
})
mnist$train$x <- mnist$train$x / 255
mnist$test$x <- mnist$test$x / 255
classifier <- linear_classifier(
feature_columns = feature_columns(
column_numeric("x", shape = shape(784L))
),
n_classes = n_classes
)
mnist_input_fn <- function(data, ...) {
input_fn(
data,
response = "y",
features = "x",
batch_size = batch_size,
...
)
}
train(classifier, input_fn = mnist_input_fn(mnist$train), steps = n_steps)
evaluate(classifier, input_fn = mnist_input_fn(mnist$test), steps = 200)
Evaluation completed after 79 steps but 200 steps was specified
average_loss | loss | global_step | accuracy |
0.35656 | 45.13418 | 100 | 0.9057 |