Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Machine Learning in Elixir - Chapter 1

machine_learning.livemd

Machine Learning in Elixir - Chapter 1

Mix.install([
  {:axon, "~> 0.5"},
  {:nx, "~> 0.5"},
  {:explorer, "~> 0.5"},
  {:kino, "~> 0.8"}
  # {:kino_explorer, "~> 0.1.8"}
])

Aliases and requires

# require(:"Elixir.Explorer.DataFrame", [{:as, :"Elixir.DF"}])
require Explorer.DataFrame, as: DF
iris = Explorer.Datasets.iris()
cols = ~w(sepal_width sepal_length petal_length petal_width)

normalized_iris =
  iris
  |> DF.mutate(
    for col <- across(^cols) do
      {col.name, (col - mean(col)) / variance(col)}
    end
  )

shuffled_normal_iris = DF.shuffle(normalized_iris)
train_df = DF.slice(shuffled_normal_iris, 0..119)
test_df = DF.slice(shuffled_normal_iris, 120..149)
feature_columns = ~w(sepal_length sepal_width petal_length petal_width)
label_column = "species"

x_train = train_df[feature_columns] |> Nx.stack(axis: 1)
x_test = test_df[feature_columns] |> Nx.stack(axis: 1)

y_train =
  train_df[label_column]
  |> Explorer.Series.cast(:category)
  |> Nx.stack(axis: -1)
  |> Nx.equal(Nx.iota({1, 3}, axis: -1))

y_test =
  test_df[label_column]
  |> Explorer.Series.cast(:category)
  |> Nx.stack(axis: -1)
  |> Nx.equal(Nx.iota({1, 3}, axis: -1))

model =
  Axon.input("iris_features")
  |> Axon.dense(3, activation: :softmax)

Axon.Display.as_graph(model, Nx.template({1, 4}, :f32))
data_stream = Stream.repeatedly(fn -> {x_train, y_train} end)

trained_model_state =
  model
  |> Axon.Loop.trainer(:categorical_cross_entropy, :sgd)
  |> Axon.Loop.metric(:accuracy)
  |> Axon.Loop.run(data_stream, %{}, iterations: 500, epochs: 10)
data = [{x_test, y_test}]

model
|> Axon.Loop.evaluator()
|> Axon.Loop.metric(:accuracy)
|> Axon.Loop.run(data, trained_model_state)