R - image data set MNIST

My dataset is MNIST from Kaggle

I am trying to use the image function for visualization by counting the first digit in a training set. Unfortunately, I get the following error:

 >image(1:28, 1:28, im, col=gray((0:255)/255)) Error in image.default(1:28, 1:28, im, col = gray((0:255)/255)) : 'z' must be numeric or logical 

Adding multiple codes:

 rawfile<-read.csv("D://Kaggle//MNIST//train.csv",header=T) #Reading the csv file im<-matrix((rawfile[1,2:ncol(rawfile)]), nrow=28, ncol=28) #For the 1st Image image(1:28, 1:28, im, col=gray((0:255)/255)) Error in image.default(1:28, 1:28, im, col = gray((0:255)/255)) : 'z' must be numeric or logical 
+5
source share
4 answers

Your im is currently a character matrix. You need to convert it to a matrix of numbers, for example. by issuing im_numbers <- apply(im, 2, as.numeric) .

Then you can image(1:28, 1:28, im_numbers, col=gray((0:255)/255)) .

+6
source

I am trying to build the same dataset using the graphics::image function. However, since the matrix is ​​usually filled so that the figure does not align properly, I wrote a function that makes the correct graph for this observation:

 #Function to visualize a number img <- function(data, row_index){ #Obtaining the row as a numeric vector r <- as.numeric(d[row_index, 2:785]) #Creating a empty matrix to use im <- matrix(nrow = 28, ncol = 28) #Filling properly the data into the matrix j <- 1 for(i in 28:1){ im[,i] <- r[j:(j+27)] j <- j+28 } #Plotting the image with the label image(x = 1:28, y = 1:28, z = im, col=gray((0:255)/255), main = paste("Number:", d[row_index, 1])) } 

I wrote this because I struggled to find a way to capture it correctly, and since I did not find it, I am sharing the function here so that others can use it.

+1
source

Make an image (1:28, 1:28, im_numbers, col = gray ((255: 0) / 255)) for a black number on a white background ... =]

0
source

Here is a small program that displays the first 36 digits of MNIST from the Keras package.

 library(keras) mnist <- dataset_mnist() x_train <- mnist$train$x y_train <- mnist$train$y # visualize the digits par(mfcol=c(6,6)) par(mar=c(0, 0, 3, 0), xaxs='i', yaxs='i') for (idx in 1:36) { im <- x_train[idx,,,1] im <- t(apply(im, 2, rev)) image(1:28, 1:28, im, col=gray((0:255)/255), xaxt='n', main=paste(y_train[idx])) } 

And the plot is as follows:

Plot

0
source

All Articles