Packages

A simple implementation of a neural network in elixir.

Current section

Files

Jump to
ex_neural_network lib ex_neural_network examples mnist.ex
Raw

lib/ex_neural_network/examples/mnist.ex

defmodule ExNeuralNetwork.Examples.Mnist do
use ExNeuralNetwork
@target [
{0.01, 0},
{0.01, 1},
{0.01, 2},
{0.01, 3},
{0.01, 4},
{0.01, 5},
{0.01, 6},
{0.01, 7},
{0.01, 8},
{0.01, 9}
]
def init() do
start_link(784, [200], 10, 0.1)
end
def train_with_file(path) do
start_time = :os.system_time(:millisecond)
path
|> read_file()
|> train_lines()
time = (:os.system_time(:millisecond) - start_time) / 1000
IO.puts("Training time in seconds: " <> Float.to_string(time))
end
def score_with_file(path) do
start_time = :os.system_time(:millisecond)
scores =
path
|> read_file()
|> score_lines()
score = (1 - Enum.sum(scores) / Enum.count(scores)) * 100
time = (:os.system_time(:millisecond) - start_time) / 1000
IO.puts(
"Error rate in percent: " <>
Float.to_string(score) <> " - Query time in seconds: " <> Float.to_string(time)
)
end
defp transform_input_node(node) do
node / 255.0 * 0.99 + 0.01
end
defp read_file(path) do
path |> File.stream!()
end
defp train_lines(lines) do
lines |> Enum.each(&train_line/1)
end
defp train_line(line) do
values = line |> String.replace("\n", "") |> String.split(",")
input =
values
|> Enum.drop(1)
|> Enum.map(fn x -> x |> String.to_integer() |> transform_input_node() end)
target_number = values |> List.first() |> String.to_integer()
target =
update_in(
@target,
[
Access.filter(fn value ->
elem(value, 1) == target_number
end)
],
fn {_, key} -> {0.99, key} end
)
|> Enum.map(fn {value, _} -> value end)
train(input, target)
end
defp score_lines(lines) do
lines |> Enum.map(&score_line/1)
end
defp score_line(line) do
values = line |> String.replace("\n", "") |> String.split(",")
expected_result = values |> Enum.at(0) |> String.to_integer()
input =
values
|> Enum.drop(1)
|> Enum.map(fn x -> x |> String.to_integer() |> transform_input_node() end)
result = query(input) |> Enum.with_index() |> Enum.max() |> elem(1)
if result == expected_result do
1
else
0
end
end
end