1
0

More than 3 years have passed since last update.

敢えてRubyで学ぶ「ゼロから作るDeep Learning」MNISTデータセット編

Last updated at Posted at 2020-02-08

「ゼロから作るDeep Learning」の72p「3.6 手書き数字認識」では、MNISTの文字のデータセットを取ってくる。読み込ませる独自のpythonのコードがモリモリ出てきて、Rubyで簡単にコード変換できない。そこで外部Gemを頼りつつ、MNISTのデータを読み込ませてみた。

Red Datasets を使う

Rubyから、機械学習の定番データセットを作ってくれるGem。MNISTの手書き数字も大量に入っている。

install

$ gem install red-datasets

ついでに画像処理用のmini_magickも入れておく

$ gem install mini_magick

中身を確認

require 'numo/narray'
require 'numo/gnuplot'
require 'datasets'
require 'mini_magick'

minst = Datasets::MNIST.new

# 1つ表示
pixels = minst.first.pixels
pixels = Numo::NArray.concatenate(pixels)
pixels = pixels.reshape(28,28)
str = Numo::UInt8.cast(pixels).to_string
img = MiniMagick::Image.import_pixels(str, 28, 28, 8, 'gray', 'png')
img.write('output.png')

出力結果

output.png

ついでに200個ならべて表示してみる

x = minst.take(200)
pixels = Numo::NArray.concatenate(Array.new(200) { |i| x[i].pixels })
pixels = pixels.reshape(10, 20, 28, 28).transpose(0, 2, 1, 3)
str = Numo::UInt8.cast(pixels).to_string

img = MiniMagick::Image.import_pixels(str, 560, 280, 8, 'gray', 'png')
img.write('output.png')

output.png

訓練データとテスト画像の生成

mnist_train = Datasets::MNIST.new(type: :train)
mnist_test = Datasets::MNIST.new(type: :test)
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0