Deep Learning from zero - 準備
import IEx.Helpers
Mix.install(
[
{:nx, "~> 0.4.0"},
{:exla, "~> 0.4.0"},
{:scidata, "~> 0.1"},
{:kino_vega_lite, "~> 0.1.7"}
],
config: [nx: [default_backend: EXLA.Backend]]
)
概要
- ゼロから作る Deep Learning ―Python で学ぶディープラーニングの理論と実装の内容を Elixir で学ぶ
資料
- https://hexdocs.pm/nx
- Nx で始めるゼロから作る Deep Learning by the_haigo
- numpyとpyplotのコード翻訳 NxとVegaでどう書くの? by the_haigo
- Elixirでディープラーニング①:手書き文字識別(MNIST)をLivebook+Axonで by piacerex
- NxでPythonっぽくAI・ML by piacerex
- Elixirにて機械学習/ディープラーニングするためのライブラリ & ツール by piacerex
よく使う関数
transpose
Nx.tensor([
[1, 2, 3],
[4, 5, 6]
])
|> Nx.transpose()
argmax
Nx.tensor([4, 5, 6]) |> Nx.argmax()
Nx.tensor(
[
[1, 2, 3],
[4, 5, 6]
],
names: [:x, :y]
)
|> Nx.argmax(axis: :y)
reshape
Nx.tensor([
[1, 2, 3],
[4, 5, 6]
])
|> Nx.reshape({3, 2})
negate
Nx.tensor([1, 2, 3]) |> Nx.negate()
グラフ描画
pyplot 代替品
-
expyplot - Python’s matplotlib.pyplot ported to Elixir
-
kino_vega_lite - Vega-Lite integration with Livebook
numpy.arange 代替品
-
Nx では
arange
関数は未実装
arange = fn start, stop, step ->
how_many = trunc((stop - start) / step)
Nx.iota({how_many})
|> Nx.multiply(step)
|> Nx.add(start)
end
x = arange2.(0, 6, 0.1)
y = Nx.sin(x)
data_to_plot = %{
x: Nx.to_flat_list(x),
y: Nx.to_flat_list(y)
}
VegaLite.new(width: 600, height: 400)
|> VegaLite.data_from_values(data_to_plot, only: ["x", "y"])
|> VegaLite.mark(:point)
|> VegaLite.encode_field(:x, "x", type: :quantitative)
|> VegaLite.encode_field(:y, "y", type: :quantitative)
データセットの読み込み
MNISTデータセットのダウンロード
{datas_raw, labels_raw} = Scidata.MNIST.download()
{data_bins, type, shape} = datas_raw
# 60,000文字分の手書き文字画像のバイナリ
<<_::binary>> = data_bins
# 文字数、バイナリの次元数、横ピクセル数、縦ピクセル数
{60000, 1, 28, 28} = shape
datas =
data_bins
|> Nx.from_binary({:u, 8})
# 一文字分の手書き文字画像データは、784ピクセル(28 x 28)の1次元行列
|> Nx.reshape({60000, 28 * 28})
|> Nx.divide(255.0)
|> dbg()
:ok
index = 6
datas[index]
# ヒートマップ表示できるよう、28x28の2次元行列に変形
|> Nx.reshape({28, 28})
|> Nx.to_heatmap()
|> dbg()
:ok