Chapter One
Mix.install([
{:axon, "~> 0.6"},
{:nx, "~> 0.6"},
{:explorer, "~> 0.7"},
{:kino, "~> 0.10"}
])
Get The Iris Dataset
require Explorer.DataFrame, as: DF
iris = Explorer.Datasets.iris()
Extract Train and Test Data
shuffled_normalized_iris =
iris
|> DF.mutate(
for col <- across(~w(sepal_length sepal_width petal_length petal_width)) do
{col.name, col - mean(col) / variance(col)}
end
)
|> DF.shuffle()
train_iris = DF.slice(shuffled_normalized_iris, 0..119)
test_iris = DF.slice(shuffled_normalized_iris, 120..149)
Extract Train and Test Features and Labels
feature_columns = ~w(sepal_length sepal_width petal_length petal_width)
train_x = Nx.stack(train_iris[feature_columns], axis: 1)
train_y =
train_iris["species"]
|> Explorer.Series.cast(:category)
|> Nx.stack(axis: -1)
|> Nx.equal(Nx.iota({1, 3}, axis: -1))
test_x = Nx.stack(test_iris[feature_columns], axis: 1)
test_y =
test_iris["species"]
|> Explorer.Series.cast(:category)
|> Nx.stack(axis: -1)
|> Nx.equal(Nx.iota({1, 3}, axis: -1))
Declare the Model
model =
Axon.input("iris_features")
|> Axon.dense(3, activation: :softmax)
Axon.Display.as_graph(model, Nx.template({1, 4}, :f32))
Train the Model
data_stream = Stream.repeatedly(fn -> {train_x, train_y} 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)
Evaluate the Model
data = [{test_x, test_y}]
evaluation =
model
|> Axon.Loop.evaluator()
|> Axon.Loop.metric(:accuracy)
|> Axon.Loop.run(data, trained_model_state)