'Predictions with TensorFlow in R - Example RStudio "Load and Preprocess data"
I am trying to make predictions on a new image for this example, however when I apply the predict() function I get an error. My code is exactly the same as in the example, and when making predictions this is my code:
# first decode the image
new_image <- "new_image.jpg" %>%
decode_img()
# predictions
predict(object = model , x = new_image)
the complete code is:
library(keras)
library(tfdatasets)
data_dir <- get_file(
origin = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz",
fname = "flower_photos.tgz",
extract = TRUE
)
data_dir <- file.path(dirname(data_dir), "flower_photos")
classes <- list.dirs(data_dir, full.names = FALSE, recursive = FALSE)
list_ds <- file_list_dataset(file_pattern = paste0(data_dir, "/*/*"))
get_label <- function(file_path) {
parts <- tf$strings$split(file_path, "/")
parts[-2] %>%
tf$equal(classes) %>%
tf$cast(dtype = tf$float32)
}
decode_img <- function(file_path, height = 224, width = 224) {
size <- as.integer(c(height, width))
file_path %>%
tf$io$read_file() %>%
tf$image$decode_jpeg(channels = 3) %>%
tf$image$convert_image_dtype(dtype = tf$float32) %>%
tf$image$resize(size = size)
}
preprocess_path <- function(file_path) {
list(
decode_img(file_path),
get_label(file_path)
)
}
labeled_ds <- list_ds %>%
dataset_map(preprocess_path, num_parallel_calls = tf$data$experimental$AUTOTUNE)
prepare <- function(ds, batch_size, shuffle_buffer_size) {
if (shuffle_buffer_size > 0)
ds <- ds %>% dataset_shuffle(shuffle_buffer_size)
ds %>%
dataset_batch(batch_size) %>%
dataset_prefetch(buffer_size = tf$data$experimental$AUTOTUNE)
}
model <- keras_model_sequential() %>%
layer_flatten() %>%
layer_dense(units = 128, activation = "relu") %>%
layer_dense(units = 128, activation = "relu") %>%
layer_dense(units = 5, activation = "softmax")
model %>%
compile(
loss = "categorical_crossentropy",
optimizer = "adam",
metrics = "accuracy"
)
model %>%
fit(
prepare(labeled_ds, batch_size = 32, shuffle_buffer_size = 1000),
epochs = 5,
verbose = 2
)
new_image <- "new_image.jpg" %>%
decode_img()
# predictions
predict(object = model , x = new_image)
It's not clear to me if what I'm doing to decode the image is causing the error.
Thank you.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
