1
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?

wslでelixir その158

Last updated at Posted at 2025-03-11

概要

wsl(wsl2じゃない)で、elixirやってみた。
練習問題やってみた。

練習問題

axonで、sin波を求めよ。

写真

image.png

setup

Mix.install(
  [
    {:nx, "~>0.9"},
    {:bumblebee, github: :"elixir-nx/bumblebee"},
    {:kino_vega_lite, "~> 0.1.7"},
    {:httpoison, "~> 1.8"},
    {:xla, "~> 0.8", XLA_BUILD: true},
    {:exla, "~> 0.9"},
    {:adbc, "~> 0.1"},
    {:kino, "~> 0.10.0"}
  ],
  config: [
    nx: [default_backend: EXLA.Backend]
  ]
)

サンプルコード

defmodule Sin do
  require Axon

  def build_model(input_shape) do
    inp1 = Axon.input("x", shape: input_shape)

    inp1
    |> Axon.dense(8, activation: :tanh)
    |> Axon.dense(1, activation: :tanh)
  end

  defp batch do
    x = Nx.tensor(for x <- 1..100, do: [x / 15])
    y = Nx.tensor(for x <- 1..100, do: [:math.sin(x / 15)])
    {x, y}
  end

  defp train_model(model, data, epochs) do
    model
    |> Axon.Loop.trainer(:mean_squared_error, :sgd)
    |> Axon.Loop.run(data, %{}, epochs: epochs, iterations: 1000)
  end

  def run() do
    model = build_model({nil})
    input_data_100 = batch()

    data =
      Stream.repeatedly(fn ->
        input_data_100
      end)

    model_state =
      train_model(model, data, 10)
      |> IO.inspect(label: "model_state")

    {x1_tensor, y1_tensor} = input_data_100
    x2_tensor = Nx.tensor(for i <- 0..100, do: [i / 15])
    y2_tensor = Axon.predict(model, model_state, %{"x" => x2_tensor})

    View.plotxy(
      Nx.to_flat_list(x1_tensor),
      Nx.to_flat_list(y1_tensor),
      Nx.to_flat_list(x2_tensor),
      Nx.to_flat_list(y2_tensor)
    )
  end
end

Sin.run()

以上。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?