0

I am having trouble plotting image fifty in R using the MNIST dataset.

  library(keras)
  mnist <- dataset_mnist()
  train_images <- mnist$train$x
  train_labels <- mnist$train$y
  test_images <- mnist$test$x
  test_labels <- mnist$test$y
  
  train_images <- array_reshape(train_images, c(60000, 28 * 28))
  train_images <- train_images / 255
  
  test_images <- array_reshape(test_images, c(10000, 28 * 28))
  test_images <- test_images / 255
  
  train_labels <- to_categorical(train_labels)
  test_labels <- to_categorical(test_labels)
  
  network <- keras_model_sequential() % % layer_dense(units = 512, 
             activation = "relu", input_shape = c(28 * 28)) % %
                                  layer_dense(units = 10, activation = "softmax")
  
  network % % compile(optimizer = "rmsprop",loss = "categorical_crossentropy", 
                                                    metrics = c("accuracy"))
  
  network % % fit(train_images, train_labels, epochs = 5, batch_size = 128)
  digit<-train_images[50,,]

Error in train_images[50, , ] : incorrect number of dimensions

I have no idea how to deal with this error message. Thanks for your help!

UseR10085
  • 7,120
  • 3
  • 24
  • 54
  • Please provide a [reproducible example in r](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). The link I provided, will tell you how. Moreover, please take the [tour](https://stackoverflow.com/tour) and visit [how to ask](https://stackoverflow.com/help/how-to-ask). Cheers. – M-- Mar 09 '19 at 21:56
  • Maybe this will do: `digit<-train_images[50 , ]` – M-- Mar 09 '19 at 21:58
  • I tried digit<-train_images[50 , ]. It didn't work. Thank you so much. – avid_live_code Mar 09 '19 at 22:34

1 Answers1

0

mnist$train$x has a dimension of (60000, 28, 28).

library(keras)
mnist <- dataset_mnist()
train_images <- mnist$train$x
dim(train_images)
# 60000    28    28

To plot the 50th image, you need to subset it.

digit <- train_images[50, 1:28, 1:28]

This will be a matrix with the dimension of 28x28. You need to transpose it first. Then you can plot with the image function.

par(pty="s") # for keeping the aspect ratio 1:1
image(t(digit), col = gray.colors(256), axes = FALSE)

Plot of a digit in MNIST dataset

Imran Kocabiyik
  • 419
  • 5
  • 15