R - 图像绘制 MNIST 数据集

10
我的数据集来自Kaggle的MNIST
我尝试使用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

添加几行代码:

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
4个回答

8

当前,您的im是一个字符矩阵。您需要将其转换为一个数字矩阵,例如通过执行im_numbers <- apply(im, 2, as.numeric)

然后您可以执行image(1:28, 1:28, im_numbers, col=gray((0:255)/255))


7
这是一个小程序,可视化了Keras包中前36个MNIST数字。
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]))
}

这个情节看起来像这样:

情节图


注:该内容涉及 IT 技术,已尽力使其通俗易懂。

3
如果您遇到此错误 Error in x_train[idx, , , 1] : incorrect number of dimensions,请将该行替换为:im <- x_train[idx,,] - Juanan

2

我一直在尝试使用graphics::image函数绘制相同的数据集。然而,由于矩阵往往以不对齐的方式填充,因此我编写了一个函数,针对给定的观察结果进行适当的绘图:

#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]))
}

我写这个函数是因为在尝试正确绘制它时遇到了困难,而且由于我没有找到解决方法,所以我在这里分享这个函数以供其他人使用。


1
只需更改您的代码中的以下内容,它就能像魔法一样运行。 img <- function(d, row_index) - honeybadger

0

对于白色背景上的黑色数字,使用image(1:28, 1:28, im_numbers, col = gray((255:0)/255))函数… =]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接