if (FALSE) {
# 1. Download sample image (dog)
norm_mean <- c(0.485, 0.456, 0.406) # ImageNet normalization constants, see
# https://pytorch.org/vision/stable/models.html
norm_std <- c(0.229, 0.224, 0.225)
img_url <- "https://en.wikipedia.org/wiki/Special:FilePath/Felis_catus-cat_on_snow.jpg"
img <- base_loader(img_url)
# 2. Convert to tensor (RGB only), resize and normalize
input <- img %>%
transform_to_tensor() %>%
transform_resize(c(224, 224)) %>%
transform_normalize(norm_mean, norm_std)
batch <- input$unsqueeze(1)
# 3. Load pretrained models
model_small <- convnext_tiny_1k(pretrained = TRUE, root = tempdir())
model_small$eval()
# 4. Forward pass
output_s <- model_small(batch)
# 5. Show Top-5 predictions
topk <- output_s$topk(k = 5, dim = 2)
indices <- as.integer(topk[[2]][1, ])
scores <- as.numeric(topk[[1]][1, ])
glue::glue("{seq_along(indices)}. {imagenet_label(indices)} ({round(scores, 2)}%)")
}
Run the code above in your browser using DataLab