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

Chapter 2

ml_in_elixir/chapter_2.livemd

Chapter 2

Mix.install([
  {:axon, "~> 0.5"},
  {:nx, "~> 0.6"},
  {:exla, "~> 0.6"},
  {:benchee, github: "bencheeorg/benchee", override: true},
  {:explorer, "~> 0.7"},
  {:kino, "~> 0.12"},
  {:kino_explorer, "~> 0.1"}
])

Section

# Initialize a 0 tensor for our heatmap
heatmap =
  Enum.map(1..50, fn _ ->
    Enum.map(1..75, fn _ -> 0 end)
  end)
  |> Nx.tensor()
#Nx.Tensor<
  s64[50][75]
  [
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
    ...
  ]
>
# Initialize tensors for the updates that we want to make and the mouse position indices
updates = Enum.map(1..50, &amp; &amp;1) |> Nx.tensor()

mouse_positions =
  Enum.map(0..49, &amp;[&amp;1, &amp;1])
  |> Nx.tensor()
#Nx.Tensor<
  s64[50][2]
  [
    [0, 0],
    [1, 1],
    [2, 2],
    [3, 3],
    [4, 4],
    [5, 5],
    [6, 6],
    [7, 7],
    [8, 8],
    [9, 9],
    [10, 10],
    [11, 11],
    [12, 12],
    [13, 13],
    [14, 14],
    [15, 15],
    [16, 16],
    [17, 17],
    [18, 18],
    [19, 19],
    [20, 20],
    [21, 21],
    [22, 22],
    [23, 23],
    [24, 24],
    ...
  ]
>
# Update our heatmap
heatmap = Nx.indexed_add(heatmap, mouse_positions, updates)
#Nx.Tensor<
  s64[50][75]
  [
    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...],
    ...
  ]
>
# View our heatmap
heatmap
|> Nx.as_type({:u, 8})
|> Nx.reshape({50, 75, 1})
|> Nx.multiply(5)
|> Kino.Image.new()