2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

概要

paiza.ioでelixirやってみた。
ニューラルネットワークで、and,or,xorの学習と推定、やってみた。

参考にしたページ

サンプルコード

defmodule NeuralNetwork do
  @lambda  1.0
  @eta     0.1
  @spec of([number],[number]) :: number
  def of(w, x) when length(w) == 3 and length(x) == 2 do
    w 
    |> Enum.zip([1, x] 
    |> List.flatten)
    |> Enum.map(fn {a, b} -> 
        a * b 
    end)
    |> Enum.sum
    |> sigmoid
  end
  @spec error_correct(number, {[number], number}) :: [number]
  def error_correct(w, {x, y}) do
    w
    |> Enum.zip([1, x] 
    |> List.flatten)
    |> Enum.map(fn {a, b} -> 
        a + @eta * (y - of(w, x) * b) 
    end) 
  end
  @spec training([number], [{[number], number}]) :: [number]
  def training(w, data), do: w |> _training(data)
  defp _training(w, []), do: w
  defp _training(w, [h | t]), do: _training(error_correct(w, h), t)
  @spec exec([number],[{[number],number}],number) :: [number]
  def exec(w, _, n) when n == 0, do: w
  def exec(w, data, n) when n > 0, do: exec(training(w, data), data, n - 1)
  def exec(_, _, _), do: false
  defp sigmoid(x), do: 1 / (1 + :math.exp(-@lambda * x))
end

alias NeuralNetwork, as: NN
w = [1, 1, 1]
and_data = [{[0, 0], 0}, {[0, 1], 0}, {[1, 0], 0}, {[1, 1], 1}]
v = w 
    |> NN.exec(and_data, 1000)
IO.puts("and")
IO.write("0, 0 : ")
NN.of(v, [0, 0])  
|> IO.inspect
IO.write("0, 1 : ")
NN.of(v, [0, 1])
|> IO.inspect
IO.write("1, 0 : ")
NN.of(v, [1, 0])
|> IO.inspect
IO.write("1, 1 : ")
NN.of(v, [1, 1])
|> IO.inspect
or_data = [{[0, 0], 0}, {[0, 1], 1}, {[1, 0], 1}, {[1, 1], 1}]
v = w 
    |> NN.exec(or_data, 1000)
IO.puts("or")
IO.write("0, 0 : ")
NN.of(v, [0, 0])
|> IO.inspect
IO.write("0, 1 : ")
NN.of(v, [0, 1])
|> IO.inspect
IO.write("1, 0 : ")
NN.of(v, [1, 0])
|> IO.inspect
IO.write("1, 1 : ")
NN.of(v, [1, 1])
|> IO.inspect

xor_data = [{[0, 0], 0}, {[0, 1], 1}, {[1, 0], 1}, {[1, 1], 0}]
v = w 
    |> NN.exec(xor_data, 1000)
IO.puts("xor")
IO.write("0, 0 : ")
NN.of(v, [0, 0])
|> IO.inspect
IO.write("0, 1 : ")
NN.of(v, [0, 1])
|> IO.inspect
IO.write("1, 0 : ")
NN.of(v, [1, 0])
|> IO.inspect
IO.write("1, 1 : ")
NN.of(v, [1, 1])
|> IO.inspect

実行結果

and
0, 0 : 1.8616738545650644e-4
0, 1 : 0.048426217768489974
1, 0 : 0.0487058890113323
1, 1 : 0.9333035631517769
or
0, 0 : 0.01050281992405151
0, 1 : 1.0
1, 0 : 1.0
1, 1 : 1.0
xor
0, 0 : 1.778830268595577e-15
0, 1 : 0.6666666666648118
1, 0 : 0.6364094670296399
1, 1 : 0.9999999999999996

成果物

以上。

2
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?