I need to select 100 examples of each digit from the mnist data base (so 100 zeros, 100 ones, 100 twos, etc), how do I do that? I've tried but I cannot find a way.
Asked
Active
Viewed 202 times
0
-
Show us what you have tried. – dcarlson Apr 28 '22 at 20:32
-
You might try this [How to read MNIST database in R?](https://stackoverflow.com/questions/21521571/how-to-read-mnist-database-in-r). – dcarlson Apr 28 '22 at 20:46
-
`library(keras) mnist <- dataset_mnist() x_train <- mnist$train$x y_train <- mnist$train$y d <- x_train[sample(y_train == 0, 100, replace = FALSE)]` – Tainara Zandoná Apr 29 '22 at 18:07
-
@dcarlson I tried the code above but it gives me a large integer instead of the 100 samples of images with label = 0 – Tainara Zandoná Apr 29 '22 at 18:13
1 Answers
0
library("keras")
library("dplyr")
#choosing just training data
mnist<-dataset_mnist()
train_images = mnist$train$x
train_labels = mnist$train$y
#prepear list for labels and 1000*28*28 array for images
mnist_labels=c()
mnist_images<-array(0,dim=c(1000,28,28))
i=1
for (x in 0:9){
#find first 100 x labels and save indexes in tempList, later append mnist_label list, mnist_images array with it
tempList=which(train_labels %in% x)%>%head(100)
for (y in tempList){
mnist_labels[i]<-train_labels[y]
mnist_images[i,1:28,1:28]<-train_images[y,1:28,1:28]
i=i+1
}
}
rm(x,y,i)
#Visualize 1th digit
first_digit<- mnist_images[1, 1:28, 1:28]
par(pty="s")
image(t(first_digit), col = gray((0:255)/255), axes= FALSE)
# visualize first 100 digits ( all zeros) if you want to get eg last 100 ( all nines, change under for loop both index with index+900)
par(mfcol=c(10,10))
par(mar=c(0, 1, 1, 0), xaxs='i', yaxs='i')
for (index in 1:100) {
im <- mnist_images[index,,]
im <- t(apply(im, 2, rev))
image(1:28, 1:28, im, col=gray((0:255)/255),
xaxt='n', main=paste(mnist_labels[index]),axes= FALSE)
}
rm(index)

Noza23
- 1