Skip to content

Commit fb67d40

Browse files
mcargianmadwellmpolvalente
authored
Add metric learning for image similarity search livebook (#613)
* Add metric learning for image similarity search example livebook * metric learning PR updates * avoid the transpose, instead contract the 8-sized axis in both tensors * Apply suggestions from code review --------- Co-authored-by: Mike Cargian <[email protected]> Co-authored-by: Paulo Valente <[email protected]>
1 parent 90b4eb6 commit fb67d40

File tree

1 file changed

+388
-0
lines changed

1 file changed

+388
-0
lines changed
Lines changed: 388 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,388 @@
1+
# Metric Learning
2+
3+
```elixir
4+
Mix.install([
5+
{:axon, "~> 0.7"},
6+
{:scidata, "~> 0.1.9"},
7+
{:exla, "~> 0.9"},
8+
{:stb_image, "~> 0.5.2"},
9+
{:kino_vega_lite, "~>0.1.13"}
10+
])
11+
12+
Nx.global_default_backend(EXLA.Backend)
13+
Nx.Defn.global_default_options(compiler: EXLA)
14+
15+
```
16+
17+
## Dataset
18+
19+
We will be using the CIFAR-10 dataset. It consists of 50,000 color images, each 32x32 pixels, divided evenly into 10 categories such as airplanes, cars, birds, and cats and another 10,000 test images.
20+
21+
```elixir
22+
{train_images, train_labels} = Scidata.CIFAR10.download()
23+
{test_images, test_labels} = Scidata.CIFAR10.download_test()
24+
```
25+
26+
After downloading the dataset, we have 50,000 training images and 10,000 test images. The images are stored in binary (`bin`) format with the shape `{50000, 3, 32, 32}`, representing 50,000 images with 3 color channels (RGB), each 32x32 pixels in size. To prepare the data for training, we normalize the pixel values by dividing by 255, scaling them from their original 0-255 range to a 0-1 range. This normalization helps the model train faster and more efficiently.
27+
28+
```elixir
29+
normalize_images = fn images ->
30+
{bin, type, shape} = images
31+
bin
32+
|> Nx.from_binary(type)
33+
|> Nx.reshape(shape, names: [:count, :channels, :width, :height])
34+
# Move channels to last position to match what conv layer expects
35+
|> Nx.transpose(axes: [:count, :width, :height, :channels])
36+
|> Nx.divide(255.0)
37+
end
38+
39+
train_images = normalize_images.(train_images)
40+
test_images = normalize_images.(test_images)
41+
42+
:ok
43+
```
44+
45+
### Create anchor, positive pairs
46+
47+
<!-- livebook:{"break_markdown":true} -->
48+
49+
In metric learning, we don’t hand the model lone examples, instead we show it sibling snapshots. Each training step picks an anchor (e.g. a random airplane photo) and a positive (another airplane shot). By treating those two as twins, the network learns to pull same-class images closer in its feature space. But to grab those pairs on the fly, we first build a simple index that groups each class label (0–9) with its image indices.
50+
51+
```elixir
52+
{bin, type, shape} = train_labels
53+
54+
class_idx_to_train_idxs =
55+
bin
56+
|> Nx.from_binary(type)
57+
|> Nx.to_flat_list()
58+
|> Enum.with_index()
59+
|> Enum.group_by(&elem(&1, 0), fn {_, i} -> i end)
60+
61+
{bin, type, shape} = test_labels
62+
63+
class_idx_to_test_idxs =
64+
bin
65+
|> Nx.from_binary(type)
66+
|> Nx.to_flat_list()
67+
|> Enum.with_index()
68+
|> Enum.group_by(&elem(&1, 0), fn {_, i} -> i end)
69+
70+
:ok
71+
72+
```
73+
74+
### Select images
75+
76+
With the index in place, the training loop draws one anchor and one sibling set from each of the 10 classes. A helper module picks them at random, for each class 0 through 9, so the model samples fresh pairs from every category each batch.
77+
78+
```elixir
79+
defmodule GetImages do
80+
def batch(train_images, class_idx_to_train_idxs) do
81+
{anchors_idx, positives_idx} =
82+
Enum.unzip(for class <- 0..9 do
83+
[a, p] = Enum.take_random(class_idx_to_train_idxs[class], 2)
84+
{a, p}
85+
end)
86+
87+
anchors = Nx.take(train_images, Nx.tensor(anchors_idx)) |> Nx.rename(nil)
88+
positives = Nx.take(train_images, Nx.tensor(positives_idx)) |> Nx.rename(nil)
89+
90+
{anchors, positives}
91+
end
92+
end
93+
94+
:ok
95+
```
96+
97+
### Example images
98+
99+
To peek into our dataset, we’ll display one anchor–positive twin from each class. We’ll use this create_kino_image helper to turn raw tensors into 64 × 64 PNG images.
100+
101+
```elixir
102+
create_kino_image = fn image ->
103+
image
104+
|> Nx.multiply(255)
105+
|> Nx.as_type(:u8)
106+
|> StbImage.from_nx()
107+
|> StbImage.resize(64, 64)
108+
|> StbImage.to_binary(:png)
109+
|> Kino.Image.new(:png)
110+
end
111+
112+
{anchors, positives} = GetImages.batch(train_images, class_idx_to_train_idxs)
113+
114+
images =
115+
[anchors, positives]
116+
|> Enum.flat_map(fn tensor ->
117+
Enum.map(0..9, fn i ->
118+
tensor
119+
|> Nx.take(Nx.tensor([i]), axis: 0)
120+
|> Nx.squeeze()
121+
|> create_kino_image.()
122+
end)
123+
end)
124+
125+
Kino.Layout.grid(images, columns: 10)
126+
```
127+
128+
### Embedding model
129+
130+
Our embedding network applies three 2D convolutional blocks (with ReLU activations and down‐sampling) before collapsing spatial dimensions via global average pooling. A final dense layer then projects into an 8-dimensional embedding space, and we ℓ₂-normalize each vector.
131+
132+
In simpler terms, our detector scans each image with a small window three times—each pass spotting edges and textures while shedding unneeded detail. It then averages those responses and feeds them into a final layer that spits out eight number vector: a compact "fingerprint." We stretch each vector so it all lives on the same unit circle, then train by showing "same" or "different" pairs—pulling matching vectors together and pushing the rest apart.
133+
134+
```elixir
135+
defmodule MetricModel do
136+
import Nx.Defn
137+
138+
def build_model do
139+
Axon.input("input", shape: {nil, 32, 32, 3})
140+
|> Axon.conv(32, kernel_size: 3, strides: 2, activation: :relu, name: "conv32")
141+
|> Axon.conv(64, kernel_size: 3, strides: 2, activation: :relu, name: "conv64")
142+
|> Axon.conv(128, kernel_size: 3, strides: 2, activation: :relu, name: "conv128")
143+
|> Axon.global_avg_pool()
144+
|> Axon.dense(8)
145+
|> Axon.nx(&normalize/1)
146+
end
147+
148+
defn normalize(x) do
149+
norm = Nx.LinAlg.norm(x, axes: [-1], keep_axes: true)
150+
Nx.divide(x, norm)
151+
end
152+
153+
end
154+
```
155+
156+
To monitor training progress, we use a KinoAxon module that plots the loss at the end of each epoch. It hooks into the training loop by handling the :epoch_completed event, extracts the current loss, and streams it to a live VegaLite chart.
157+
158+
```elixir
159+
alias VegaLite, as: Vl
160+
161+
defmodule KinoAxon do
162+
def plot_losses(loop) do
163+
vl_widget =
164+
Vl.new(width: 600, height: 400)
165+
|> Vl.mark(:point, tooltip: true)
166+
|> Vl.encode_field(:x, "epoch", type: :ordinal, title: "Epoch")
167+
|> Vl.encode_field(:y, "loss",
168+
type: :quantitative,
169+
scale: [zero: false, nice: true],
170+
title: "Loss"
171+
)
172+
|> Vl.encode_field(:color, "dataset", type: :nominal)
173+
|> Kino.VegaLite.new()
174+
|> Kino.render()
175+
176+
handler = fn state ->
177+
%Axon.Loop.State{epoch: epoch, iteration: _iter, step_state: step_state} = state
178+
Kino.VegaLite.push_many(vl_widget, [%{epoch: epoch, loss: Nx.to_number(step_state[:epoch_avg_loss]), dataset: "train"}])
179+
{:continue, state}
180+
end
181+
182+
Axon.Loop.handle_event(loop, :epoch_completed, handler)
183+
end
184+
end
185+
```
186+
187+
### Embedding Model
188+
189+
We wrap our model in a custom train_step that does three things each batch:
190+
191+
* Embed both anchors and positives through the network.
192+
* Score them by taking dot products (our raw “how-similar?” numbers).
193+
* Compute a softmax cross-entropy loss over those scores—using temperature scaling to sharpen or soften the comparison.
194+
195+
The training loop then uses that loss to nudge parameters, pulling same-class vectors together and pushing others apart, one batch at a time.
196+
197+
```elixir
198+
defmodule MetricLearning do
199+
import Nx.Defn
200+
require Logger
201+
202+
defn objective_fn(predict_fn, params, {anchor, positive}) do
203+
%{prediction: anchor_embeddings} = predict_fn.(params, %{"input" => anchor})
204+
%{prediction: positive_embeddings} = predict_fn.(params, %{"input" => positive})
205+
206+
similarities = Nx.dot(anchor_embeddings, [1], positive_embeddings, [1])
207+
temperature = 0.2
208+
similarities = similarities / temperature
209+
sparse_labels = Nx.iota({10})
210+
211+
Axon.Losses.categorical_cross_entropy(sparse_labels, similarities,
212+
reduction: :mean,
213+
sparse: true,
214+
from_logits: true
215+
)
216+
end
217+
218+
defn batch_step(predict_fn, optim, {anchor, positive}, state) do
219+
# Compute gradient of objective defined above
220+
{loss, gradients} =
221+
value_and_grad(state.model_state, &objective_fn(predict_fn, &1, {anchor, positive}))
222+
223+
{updates, new_optimizer_state} = optim.(gradients, state.optimizer_state, state.model_state)
224+
new_params = Polaris.Updates.apply_updates(state.model_state, updates)
225+
226+
%{
227+
state
228+
| model_state: new_params,
229+
optimizer_state: new_optimizer_state,
230+
epoch_loss: state[:epoch_loss] + loss,
231+
epoch_count: state[:epoch_count] + 1,
232+
epoch_avg_loss: (state[:epoch_loss] + loss) / (state[:epoch_count] + 1)
233+
}
234+
end
235+
236+
def init(template, init_fn, init_optim) do
237+
model_state = init_fn.(template, Axon.ModelState.empty())
238+
239+
%{
240+
model_state: model_state,
241+
optimizer_state: init_optim.(model_state),
242+
epoch_loss: Nx.tensor(0.0),
243+
epoch_count: Nx.tensor(0),
244+
epoch_avg_loss: Nx.tensor(0.0)
245+
}
246+
end
247+
248+
def run(train_images, class_idx_to_train_idxs) do
249+
250+
{optim_init_fn, optim_update_fn} = Polaris.Optimizers.adam()
251+
{init_fn, predict_fn} = Axon.build(MetricModel.build_model(), mode: :train, debug: false)
252+
253+
step = &batch_step(predict_fn, optim_update_fn, &1, &2)
254+
init = fn {template, _}, _state -> init(%{"input" => template}, init_fn, optim_init_fn) end
255+
256+
training_data = Stream.repeatedly(fn ->
257+
GetImages.batch(train_images, class_idx_to_train_idxs)
258+
end)
259+
260+
final_state =
261+
Axon.Loop.loop(step, init)
262+
|> Axon.Loop.log(
263+
fn %Axon.Loop.State{epoch: epoch, step_state: state} ->
264+
loss_str = :io_lib.format(~c"~.4f", [Nx.to_number(state[:epoch_avg_loss])])
265+
"\rEpoch: #{epoch}, Loss: #{loss_str}\n"
266+
end,
267+
event: :epoch_completed
268+
)
269+
|> KinoAxon.plot_losses()
270+
|> Axon.Loop.run(training_data, %{}, iterations: 1000, epochs: 20, compiler: EXLA)
271+
272+
{final_state, predict_fn}
273+
274+
end
275+
276+
end
277+
278+
{final_state, predict_fn} = MetricLearning.run(train_images, class_idx_to_train_idxs)
279+
280+
:ok
281+
```
282+
283+
### Testing
284+
285+
After training, we pass every test image through our network to get its embedding. We then build a "who’s most like whom" table by dot-producting each embedding against all the others, and finally call Nx.top_k to pull out the ten closest cousins for each image.
286+
287+
```elixir
288+
final_params = final_state.step_state.model_state
289+
near_neighbors_per_example = 10
290+
%{prediction: embeddings} = predict_fn.(final_params, %{"input" => test_images})
291+
292+
embeddings = Nx.rename(embeddings, [nil, nil])
293+
gram_matrix = Nx.dot(embeddings, [1], embeddings, [1])
294+
295+
{_vals, neighbors} = Nx.top_k(gram_matrix, k: near_neighbors_per_example + 1)
296+
297+
:ok
298+
```
299+
300+
To visually inspect how well our embeddings capture similarity, we create a collage for each of the ten classes. For each class, we pick the first example in each class and place it in the first column. Then, in the next ten columns, we display its ten closest neighbors to see which images the network considers its nearest matches.
301+
302+
```elixir
303+
# take first image of each class
304+
example_per_class_idx =
305+
0..9
306+
|> Enum.map(fn class_idx ->
307+
class_idx_to_test_idxs[class_idx] |> Enum.at(0)
308+
end)
309+
|> Nx.tensor(type: {:s, 64})
310+
311+
# take nearest neighbors for each example
312+
neighbors_for_samples = Nx.take(neighbors, example_per_class_idx, axis: 0)
313+
314+
neighbour_idxs =
315+
neighbors_for_samples
316+
|> Nx.to_flat_list()
317+
318+
images =
319+
for idx <- neighbour_idxs do
320+
test_images[idx]
321+
|> Nx.squeeze()
322+
|> Nx.transpose(axes: [:width, :height, :channels])
323+
|> create_kino_image.()
324+
end
325+
326+
Kino.render(Kino.Layout.grid(images, columns: 11))
327+
328+
:ok
329+
```
330+
331+
### Confusion Matrix
332+
333+
To measure performance numerically, we treat each example’s nearest neighbors as a simple classifier and summarize the results in a confusion matrix. We pick ten images from each of the ten classes, find the ten closest embeddings for each one, and ask: “Do these neighbors share the same label as our query image?” Each group of the predicted classes is compared against the true class to populate the matrix.
334+
335+
```elixir
336+
{bin, type, shape} = test_labels
337+
test_labels_tensor =
338+
bin
339+
|> Nx.from_binary(type)
340+
|> Nx.reshape(shape)
341+
342+
# take 10 images from each class in the test set
343+
test_idxs =
344+
0..9
345+
|> Enum.flat_map(fn class_idx ->
346+
class_idx_to_test_idxs[class_idx]
347+
|> Enum.take(10)
348+
end)
349+
350+
# 100 copies of each class (for 10 neighbors per 10 examples)
351+
actual_classes =
352+
0..9
353+
|> Enum.flat_map(fn class_idx ->
354+
List.duplicate(class_idx, 100) # 100 copies of each class_idx
355+
end)
356+
357+
predicted_classes =
358+
neighbors
359+
|> Nx.take(Nx.tensor(test_idxs), axis: 0)
360+
|> Nx.slice([0, 1], [100, 10]) # 100 examples × 10 neighbors, skip self
361+
|> Nx.to_flat_list()
362+
|> Enum.map(fn idx -> Nx.to_number(test_labels_tensor[idx]) end)
363+
364+
Vl.new(title: "Confusion Matrix", width: 700, height: 700)
365+
|> Vl.data_from_values(%{
366+
predicted: predicted_classes,
367+
actual: actual_classes
368+
})
369+
|> Vl.layers([
370+
# First layer: draw the rects with color encoding
371+
Vl.new()
372+
|> Vl.mark(:rect, tooltip: false)
373+
|> Vl.encode_field(:x, "predicted", title: "Predicted Label")
374+
|> Vl.encode_field(:y, "actual", title: "True Label")
375+
|> Vl.encode(:color, aggregate: :count, legend: [title: "Matches"]),
376+
377+
# Second layer: add the count as centered text
378+
Vl.new()
379+
|> Vl.mark(:text,
380+
align: "center",
381+
baseline: "middle",
382+
font_size: 16
383+
)
384+
|> Vl.encode_field(:x, "predicted")
385+
|> Vl.encode_field(:y, "actual")
386+
|> Vl.encode(:text, aggregate: :count)
387+
])
388+
```

0 commit comments

Comments
 (0)