t12a
Hi,
I’m reading the book Programming Machine Learning and trying to translate examples in Elixir using Nx.
Here is the code I exported from my Livebook.
Linear Regression
Mix.install([
{:nx, "~> 0.4.2"},
{:axon, "~> 0.4.1"},
{:explorer, "~> 0.5.0"},
{:kino, "~> 0.8.0"},
{:vega_lite, "~> 0.1.6"},
{:kino_vega_lite, "~> 0.1.7"}
])
Data
csv = """
Reservations,Pizzas
13,33
2,16
14,32
23,51
13,27
1,16
18,34
10,17
26,29
3,15
3,15
21,32
7,22
22,37
2,13
27,44
6,16
10,21
18,37
15,30
9,26
26,34
8,23
15,39
10,27
21,37
5,17
6,18
13,25
13,23
"""
{:ok, data} =
csv
|> Explorer.DataFrame.load_csv()
reserv = data["Reservations"]
pizzas = data["Pizzas"]
Let’s plot the actual values and our first attempt to model.
weight_text = Kino.Input.text("Weight", default: "1")
alias VegaLite, as: Vl
{weight, _} = Float.parse(Kino.Input.read(weight_text))
model = Explorer.DataFrame.new(iter: 1..Explorer.Series.max(reserv))
chart1 =
Vl.new()
|> Vl.data_from_values(data, only: ["Reservations", "Pizzas"])
|> Vl.mark(:point)
|> Vl.encode_field(:x, "Reservations", type: :quantitative)
|> Vl.encode_field(:y, "Pizzas", type: :quantitative)
chart2 =
Vl.new()
|> Vl.data_from_values(model, only: ["iter", "weights"])
|> Vl.transform(calculate: "datum.iter * #{weight}", as: "weights")
|> Vl.mark(:line)
|> Vl.encode_field(:x, "iter", type: :quantitative)
|> Vl.encode_field(:y, "weights", type: :quantitative)
combined =
Vl.new(width: 400, height: 300)
|> Vl.layers([chart1, chart2])
This is how VegaLite creates a linear regression.
Vl.new(width: 400, height: 300)
|> Vl.data_from_values(
reservations: Explorer.Series.to_list(reserv),
pizzas: Explorer.Series.to_list(pizzas)
)
|> Vl.layers([
Vl.new()
|> Vl.mark(:point, filled: true)
|> Vl.encode_field(:x, "reservations", type: :quantitative)
|> Vl.encode_field(:y, "pizzas", type: :quantitative),
Vl.new()
|> Vl.mark(:line, color: :firebrick)
|> Vl.transform(regression: "pizzas", on: "reservations")
|> Vl.encode_field(:x, "reservations", type: :quantitative)
|> Vl.encode_field(:y, "pizzas", type: :quantitative)
])
Predict and Loss
defmodule MachineLearning do
def predict(x, w, b) do
x
|> Nx.multiply(w)
|> Nx.add(b)
end
def loss(x, y, w, b) do
# basically mean squared error
predict(x, w, b)
|> Nx.subtract(y)
|> Nx.power(2)
|> Nx.mean()
end
def train(x, y, iter, lr) do
# initialize weights and biases to 0
Enum.reduce_while(1..iter, {0.0, 0.0}, fn i, {w, b} ->
current_loss = loss(x, y, w, b)
IO.puts("Iter ##{i} => Loss: #{inspect(current_loss)}")
cond do
loss(x, y, w + lr, b) < current_loss ->
{:cont, {w + lr, b}}
loss(x, y, w - lr, b) < current_loss ->
{:cont, {w - lr, b}}
loss(x, y, w, b + lr) < current_loss ->
{:cont, {w, b + lr}}
loss(x, y, w, b - lr) < current_loss ->
{:cont, {w, b - lr}}
true ->
{:halt, {w, b}}
end
end)
end
end
reserv_t = Nx.tensor(Explorer.Series.to_list(reserv))
pizzas_t = Nx.tensor(Explorer.Series.to_list(pizzas))
MachineLearning.train(reserv_t, pizzas_t, 50, 0.1)
I could not properly make it work on the training part, it always stops the training after a few iterations. Where do you think I get it wrong?
Trending in Questions
Hey guys,
I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly
Do you guys have any suggestions what is the best prac...
New
Hello!
Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app.
I creat...
New
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
Anyone here using Honeybadger?
My Honeybadger account is being overwhelmed with noise from some bots. Seeing a lot of
Bandit.HTTPError...
New
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
Other Trending Topics
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hobbes is a low-level distributed database for the Elixir programming language.
Hobbes provides a simple, safe, and scalable storage lay...
New
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve.
They are GUI (Emerge) and State management (S...
New
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
There are three potential reasons for members of this forum to have a look at https://vutuv.de
You are tired or annoyed of LinkedIn.
Yo...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #blog-post
- #elixir-ls
- #elixirconf-us
- #ai
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming










Showing Posts 1 to 4- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
polvalente
Because you’re using def and not defn, your loss function is returning an Nx.Tensor struct ane not a number. By using the standard comparison operators, you’re comparing numbers and structs, so that will fail fast because numbers are always evaluated as less than structs in Elixir
I strongly advise you to try and rewrite everything with
defn, replacing the Enum.reduce_while withwhile.Otherwise, look into using Nx.to_number so that your comparisons work properly.
t12a
I just want to add more context on this. This is the output that I ended up with.
As you can see, it stops at 2nd iteration.
And here is the python version of the code from the book
polvalente
The main difference between Nx and Python is that Python has the concept of operator overloading that Elixir doesn’t. So when you have
def lossreturning a numpy array and compare it with< current_loss, you get numpy to do the comparison correctly.In Nx, because your using
def lossanddef train, you’re actually comparing 2 Nx.Tensor structs with the default Elixir comparison operator. That will not work semantically, the same reason that comapring two DateTime structs doesn’t work properly.You need to fix this by turning your code to
defn, which replaces the default Kernel withNx.Defn.Kernel.NickGnd
Hey @t12a
I’m writing you since I just published a collection of livebooks for the book you are reading (Programming Machine Learning by P. Perrotta) in case you are curious you can find them in this GH repository GitHub - nickgnd/programming-machine-learning-livebooks: Programming Machine Learning - Elixir Livebooks · GitHub
Have a great day