手写数字识别数据集

# 读取数据集
load_mnist()

查看数据集

str(train)
List of 3
 $ n: int 60000
 $ x: int [1:60000, 1:784] 0 0 0 0 0 0 0 0 0 0 ...
 $ y: int [1:60000] 5 0 4 1 9 2 1 3 1 4 ...
str(test)
List of 3
 $ n: int 10000
 $ x: int [1:10000, 1:784] 0 0 0 0 0 0 0 0 0 0 ...
 $ y: int [1:10000] 7 2 1 0 4 1 4 9 5 9 ...

第一个样本,是手写数字5,每个图像的尺寸 28*28 = 784 像素的

png(filename = "mnist-five.png", res = 150, type = "cairo")
op <- par(mar = rep(0.1, 4))
show_digit(train$x[1,], ann = F, axes = F)
par(op)
dev.off()

手写数字5

随机选择 400 个训练样本展示如下

png(filename = "sub-mnist.png", width = 20*80, height = 20*80, res = 150, type = "cairo")
op <- par(mfrow = c(20, 20), mar = rep(0.1, 4))
for (i in sample(1:nrow(train$x), size = 20*20, replace = FALSE)) {
  show_digit(train$x[i, ], ann = F, axes = F)
}
par(op)
dev.off()

随机选择400个子样本

附录

MNIST 数据集来自 http://yann.lecun.com/exdb/mnist/ 网站还有一个完整的测试 KNN SVM CNN 等算法

读取手写数字数据集,下面这段代码来自 https://gist.github.com/brendano/39760 授权协议是 MIT 协议,原用于读取 MNIST 数据集,现在也可用于读取 Fashion-MNIST 数据集

# Load the MNIST digit recognition dataset into R
# http://yann.lecun.com/exdb/mnist/
# assume you have all 4 files and gunzip'd them
# creates train$n, train$x, train$y  and test$n, test$x, test$y
# e.g. train$x is a 60000 x 784 matrix, each row is one digit (28x28)
# call:  show_digit(train$x[5,])   to see a digit.
# brendan o'connor - gist.github.com/39760 - anyall.org

load_mnist <- function() {
  load_image_file <- function(filename) {
    ret = list()
    f = file(filename,'rb')
    readBin(f,'integer',n=1,size=4,endian='big')
    ret$n = readBin(f,'integer',n=1,size=4,endian='big')
    nrow = readBin(f,'integer',n=1,size=4,endian='big')
    ncol = readBin(f,'integer',n=1,size=4,endian='big')
    x = readBin(f,'integer',n=ret$n*nrow*ncol,size=1,signed=F)
    ret$x = matrix(x, ncol=nrow*ncol, byrow=T)
    close(f)
    ret
  }
  load_label_file <- function(filename) {
    f = file(filename,'rb')
    readBin(f,'integer',n=1,size=4,endian='big')
    n = readBin(f,'integer',n=1,size=4,endian='big')
    y = readBin(f,'integer',n=n,size=1,signed=F)
    close(f)
    y
  }
  train <<- load_image_file('mnist/train-images-idx3-ubyte')
  test <<- load_image_file('mnist/t10k-images-idx3-ubyte')
  
  train$y <<- load_label_file('mnist/train-labels-idx1-ubyte')
  test$y <<- load_label_file('mnist/t10k-labels-idx1-ubyte')  
}

show_digit <- function(arr784, col=gray(12:1/12), ...) {
  image(matrix(arr784, nrow=28)[,28:1], col=col, ...)
}

Fashion-MNIST 数据集同样以 MIT 授权协议发布,同时数据格式和 MNIST 一样,希望作为 MNIST 的替代,下载链接 https://www.kaggle.com/zalando-research/fashionmnist/version/4