【问题标题】:R - Image Plot MNIST datasetR - 图像绘图 MNIST 数据集
【发布时间】:2016-10-23 13:06:32
【问题描述】:

我的数据集是来自 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

【问题讨论】:

    标签: r image mnist kaggle


    【解决方案1】:

    目前你的 im 是一个字符矩阵。您需要将其转换为数字矩阵,例如通过发出im_numbers &lt;- apply(im, 2, as.numeric)

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

    【讨论】:

      【解决方案2】:

      这是一个小程序,它可以可视化 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]))
      }
      

      情节是这样的:

      【讨论】:

      • 如果您收到此错误Error in x_train[idx, , , 1] : incorrect number of dimensions,只需将该行替换为:im
      【解决方案3】:

      我一直在尝试使用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]))
      }
      

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

      【讨论】:

      • 只需在您的代码中更改以下内容,它就像一个魅力。 img
      【解决方案4】:

      为白色背景上的黑色数字做 image(1:28, 1:28, im_numbers, col=gray((255:0)/255)) ... =]

      【讨论】:

        猜你喜欢
        • 2017-01-10
        • 2021-10-05
        • 2017-12-29
        • 2018-08-06
        • 2022-01-01
        • 2018-09-11
        • 2016-11-13
        • 1970-01-01
        • 2021-05-14
        相关资源
        最近更新 更多