Code
# on Google Colab, PyTorch comes preinstalled; timm and umap-learn may not
import sys
if "google.colab" in sys.modules:
!pip install -q timm umap-learnColab link
In classes 6 and 7 we saw that neural networks turn images (and text) into high-dimensional vectors. Today we’ll take a close look at these vectors: embeddings.
Plan
import os
os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1") # cleaner output when downloading from Hugging Face
os.environ.setdefault("HF_HUB_VERBOSITY", "error")
import time
import base64
import zipfile
import warnings
from io import BytesIO
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
import torch.nn.functional as F
from PIL import Image
from skimage import data, io
import timm
from huggingface_hub import hf_hub_download
# chart colors and style
AZUL, LARANJA, VERDE, CINZA, TINTA = "#2a78d6", "#eb6834", "#1baf7a", "#898781", "#52514e"
plt.rcParams.update({
"axes.spines.top": False, "axes.spines.right": False,
"axes.edgecolor": CINZA, "axes.labelcolor": TINTA,
"xtick.color": TINTA, "ytick.color": TINTA,
"axes.grid": True, "grid.color": "#e6e5e1", "figure.dpi": 110,
})
warnings.filterwarnings("ignore", message=".*n_jobs value.*") # UMAP warning when fixing random_state
torch.manual_seed(0)
DEVICE = "cuda" if torch.cuda.is_available() else ("mps" if torch.backends.mps.is_available() else "cpu")
# the LandCover.ai dataset (class 6): already in the Hugging Face cache if you ran that class
PASTA_LC = "data/landcoverai"
if not os.path.exists(PASTA_LC):
caminho = hf_hub_download(repo_id="isaaccorley/landcoverai", filename="landcoverai100.zip", repo_type="dataset")
zipfile.ZipFile(caminho).extractall(PASTA_LC)
ids = {s: open(f"{PASTA_LC}/{s}.txt").read().split() for s in ["train", "val", "test"]}
NOMES_LC = ["background", "building", "forest", "water", "road"]
CORES_LC = ["#d9d9d9", "#e34948", "#1baf7a", "#2a78d6", "#eda100"]
# the pre-trained ResNet-50 from class 6
resnet50 = timm.create_model("hf-hub:timm/resnet50.a1_in1k", pretrained=True).eval()
config = timm.data.resolve_data_config({}, model=resnet50)
transformacao = timm.data.create_transform(**config)
media, desvio = torch.tensor(config["mean"])[:, None, None], torch.tensor(config["std"])[:, None, None]
normaliza = lambda x: (x - media) / desvio
print(f"PyTorch {torch.__version__} | device: {DEVICE} | ResNet-50 with {sum(p.numel() for p in resnet50.parameters()) / 1e6:.1f} M parameters")PyTorch 2.14.1 | dispositivo: mps | ResNet-50 com 25.6 M parâmetros
All the architectures from class 6 do the same thing inside: they turn the input into a vector in a high-dimensional space.
The U-Net encoder’s 1024-channel maps, the vector of 2,048 numbers that ResNet-50 produces before the classification layer, a Transformer’s tokens: all of these are representations of the input.
Let’s focus on that word, representation, because in a way that’s what embeddings are: representations of the input in a high-dimensional space.
So an object is represented by a high-dimensional vector. That vector is called an embedding.
There’s one property that makes embeddings useful:
similar objects end up close together in the embedding space.
“Close” here is usually measured with cosine similarity (Part 5).
Embeddings work like a map, only with 2,048 axes instead of 2. What these many dimensions actually mean is still an open question: nobody chooses the meaning of any one dimension; they emerge during model training and capture relationships that are yet to be understood.
As we saw with ResNet-50, the embedding is the output of global average pooling (class 6, section 2.6): the 2,048 maps of the last convolutional layer, each summarized by its mean. It’s the input of the last linear layer, the one that chooses among ImageNet’s 1,000 classes. So the ResNet embedding is a 2,048-dimensional vector. Let’s look into it:
resnet50 = resnet50.to(DEVICE).eval()
@torch.no_grad()
def embedding(lote_imagens):
"""lote_imagens: (N, 3, 224, 224) already normalized → (N, 2048)."""
mapas = resnet50.forward_features(lote_imagens.to(DEVICE)) # (N, 2048, 7, 7)
return resnet50.forward_head(mapas, pre_logits=True).cpu() # global average pooling (N, 2048)
x = transformacao(Image.fromarray(data.chelsea())).unsqueeze(0)
with torch.no_grad():
print(f"maps of the last convolutional layer: {tuple(resnet50.forward_features(x.to(DEVICE)).shape)}")
e = embedding(x)
print(f"cat embedding: {tuple(e.shape)}")
print(f"first 8 of the 2,048 numbers: {e[0, :8].numpy().round(2)}")
print(f"{(e == 0).float().mean():.0%} of the numbers are zero: the last layer goes through a ReLU, and each image activates only some of the 2,048 detectors")mapas da última camada convolucional: (1, 2048, 7, 7)
embedding do gato: (1, 2048)
primeiros 8 dos 2.048 números: [0. 0. 0. 0. 0. 0. 0. 0.12]
65% dos números são zero: a última camada passa por uma ReLU, e cada imagem ativa só parte dos 2.048 detectores
We cut the 100 LandCover.ai images into 128 × 128 pixel tiles (16 per image) and compute the embedding of each tile with the pre-trained ResNet-50.
Each tile gets as its “label” the most frequent class among its pixels, and we keep only the tiles where that class covers at least 60% of the area. Buildings and roads are too narrow to dominate a whole tile, so in this section three classes remain: background, forest and water.
TILE = 128
todos_ids = ids["train"] + ids["val"] + ids["test"]
tiles, classes_tile, origem = [], [], []
for img_id in todos_ids:
img = torch.tensor(io.imread(f"{PASTA_LC}/output/{img_id}.jpg")).permute(2, 0, 1).float() / 255
mascara = torch.tensor(io.imread(f"{PASTA_LC}/output/{img_id}_m.png")[..., 0]).long()
for i in range(0, 512, TILE):
for j in range(0, 512, TILE):
contagem = torch.bincount(mascara[i:i + TILE, j:j + TILE].flatten(), minlength=5)
classe = int(contagem.argmax())
if contagem[classe] / contagem.sum() >= 0.6:
tiles.append(img[:, i:i + TILE, j:j + TILE])
classes_tile.append(classe)
split = "train" if img_id in ids["train"] else "teste"
origem.append((img_id, split))
tiles = torch.stack(tiles)
classes_tile = np.array(classes_tile)
print(f"{len(tiles)} tiles of {TILE} × {TILE}:", {NOMES_LC[c]: int((classes_tile == c).sum()) for c in range(5)})
# buildings and roads almost never cover 60% of a tile: we keep only classes with at least 20 tiles
fica = np.isin(classes_tile, [c for c in range(5) if (classes_tile == c).sum() >= 20])
tiles, classes_tile = tiles[torch.tensor(fica)], classes_tile[fica]
origem = [o for o, f in zip(origem, fica) if f]
split_tile = np.array([s for _, s in origem])
print(f"we keep {len(tiles)} tiles:", {NOMES_LC[c]: int((classes_tile == c).sum()) for c in np.unique(classes_tile)})
inicio = time.time()
entrada = normaliza(F.interpolate(tiles, size=224, mode="bilinear", antialias=True)) # ResNet-50 expects 224 × 224
embeddings = torch.cat([embedding(entrada[k:k + 64]) for k in range(0, len(entrada), 64)])
print(f"embeddings: {tuple(embeddings.shape)} ({time.time() - inicio:.0f} s)")1477 pedaços de 128 × 128: {'fundo': 964, 'edificação': 2, 'floresta': 394, 'água': 116, 'estrada': 1}
ficamos com 1474 pedaços: {'fundo': 964, 'floresta': 394, 'água': 116}
embeddings: (1474, 2048) (11 s)
We now have a table: each row is an image tile, each of the 2,048 columns is an embedding dimension. It’s the same format as the tables from the Machine Learning classes, except with columns that nobody chose: they were learned by ResNet-50.
tabela de embeddings: 1474 linhas × 2048 colunas (mostrando 8)
| classe | dim_0 | dim_1 | dim_2 | dim_3 | dim_4 | dim_5 | dim_6 | dim_7 | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | fundo | 0.000000 | 0.0 | 0.000000 | 0.000000 | 0.008112 | 0.000000 | 0.033004 | 0.281517 |
| 1 | fundo | 0.043476 | 0.0 | 0.000000 | 0.000000 | 0.012554 | 0.004839 | 0.017236 | 0.265829 |
| 2 | fundo | 0.000000 | 0.0 | 0.000000 | 0.074292 | 0.001053 | 0.000000 | 0.070094 | 0.132552 |
| 3 | fundo | 0.000000 | 0.0 | 0.000000 | 0.000000 | 0.000000 | 0.002391 | 0.047818 | 0.151173 |
| 4 | fundo | 0.002209 | 0.0 | 0.001979 | 0.000000 | 0.021305 | 0.000000 | 0.022902 | 0.224125 |
Working with 2,048 dimensions has three problems:
rng = np.random.default_rng(0)
fig, ax = plt.subplots(figsize=(10, 4))
linhas = []
for dim, cor in zip([2, 10, 100, 2048], [AZUL, VERDE, LARANJA, "#4a3aa7"]):
pontos = torch.tensor(rng.random((500, dim)))
dist = torch.cdist(pontos, pontos).numpy()[np.triu_indices(500, k=1)]
ax.hist(dist / dist.mean(), bins=80, histtype="step", lw=2, color=cor, density=True, label=f"{dim} dimensions")
linhas.append({"dimensões": dim, "mais perto / mais longe": f"{dist.min() / dist.max():.2f}"})
ax.set(xlabel="distance between pairs of points (divided by the mean distance)", ylabel="density",
title="500 random points: in many dimensions, all distances become similar", xlim=(0, 2.5))
ax.legend(frameon=False)
plt.show()
pd.DataFrame(linhas)
| dimensões | mais perto / mais longe | |
|---|---|---|
| 0 | 2 | 0.00 |
| 1 | 10 | 0.12 |
| 2 | 100 | 0.60 |
| 3 | 2048 | 0.89 |
In 2 dimensions, there are very close and very distant pairs. In 2,048, almost all distances are close to the mean: the closest pair is almost as far apart as the farthest pair.
The good news: embeddings of real data are not random points. They occupy a much smaller region of the space (like a crumpled sheet of paper inside a room), and dimensionality reduction methods try to “uncrumple” that sheet. Let’s compare the three most widely used.
PCA looks for the directions of greatest variation in the data. The 1st component is the direction in which the points spread the most; the 2nd is the direction of greatest variation perpendicular to the first, and so on. Projecting the data onto the first 2 is like taking the most informative possible “photo” of a 3D object.
transform: projects new points onto the same map.from sklearn.decomposition import PCA
inicio = time.time()
pca = PCA().fit(embeddings.numpy())
xy_pca = pca.transform(embeddings.numpy())[:, :2]
tempo_pca = time.time() - inicio
var_acum = np.cumsum(pca.explained_variance_ratio_)
n90 = int(np.searchsorted(var_acum, 0.9)) + 1
classes_presentes = np.unique(classes_tile)
cores_pontos = {0: "#898781", 1: CORES_LC[1], 2: CORES_LC[2], 3: CORES_LC[3], 4: CORES_LC[4]} # background in dark gray
def desenha_projecao(ax, xy, titulo):
for c in classes_presentes:
m = classes_tile == c
ax.scatter(xy[m, 0], xy[m, 1], s=8, color=cores_pontos[c], alpha=0.7, label=NOMES_LC[c])
ax.set(title=titulo, xticks=[], yticks=[])
ax.grid(False)
fig, axes = plt.subplots(1, 2, figsize=(15, 5))
axes[0].plot(np.arange(1, len(var_acum) + 1), var_acum, color=AZUL, lw=2)
axes[0].axhline(0.9, color=CINZA, ls="--", lw=1)
axes[0].axvline(n90, color=CINZA, ls="--", lw=1)
axes[0].text(n90 * 1.15, 0.5, f"{n90} components\nexplain 90% of the variation", color=TINTA)
axes[0].set(xscale="log", xlabel="number of components", ylabel="explained variation (cumulative)",
title="How much each component explains", ylim=(0, 1.02))
desenha_projecao(axes[1], xy_pca, f"PCA: first 2 components ({var_acum[1]:.0%} of the variation)")
axes[1].legend(frameon=False, markerscale=2.5)
plt.tight_layout()
plt.show()
print(f"PCA in {tempo_pca:.1f} s")
PCA em 0.2 s
Reading the plots: the first 2 components explain only a small part of the total variation; to keep 90% of the information we need about 200 components, far fewer than 2,048. On the map, forest and water already separate from the background, but the groups overlap a lot: the structure of the embeddings isn’t linear.
In practice: PCA is rarely the final map, but it’s a great first step: reducing from 2,048 to ~50 dimensions removes noise and speeds up t-SNE and UMAP.
t-SNE (2008) doesn’t try to preserve distances, but neighborhoods. In short:
transform for new points.perplexity, roughly the number of neighbors each point “considers” (5 to 50).from sklearn.manifold import TSNE
emb_pca50 = PCA(n_components=50, random_state=0).fit_transform(embeddings.numpy()) # PCA first: faster and less noise
fig, axes = plt.subplots(1, 3, figsize=(16, 5))
for ax, perp in zip(axes, [5, 30, 100]):
inicio = time.time()
xy = TSNE(n_components=2, perplexity=perp, init="pca", random_state=0).fit_transform(emb_pca50)
if perp == 30:
xy_tsne, tempo_tsne = xy, time.time() - inicio
desenha_projecao(ax, xy, f"t-SNE, perplexity = {perp} ({time.time() - inicio:.1f} s)")
axes[0].legend(frameon=False, markerscale=2.5)
plt.tight_layout()
plt.show()
With a small perplexity, t-SNE breaks the data into many little groups (it only looks at immediate neighbors); with a large perplexity, the groups become more cohesive and the overall organization shows up better. There’s no “right” value: it’s worth trying a few.
UMAP (2018) has an idea similar to t-SNE’s, with different math:
n_neighbors nearest);transform: projects new points onto an existing map.n_neighbors (local × global, like perplexity) and min_dist (how tightly points can pack together on the map).(On the first run, UMAP takes a few extra seconds to compile its code.)
import umap
fig, axes = plt.subplots(1, 3, figsize=(16, 5))
for ax, viz in zip(axes, [5, 15, 50]):
inicio = time.time()
xy = umap.UMAP(n_neighbors=viz, min_dist=0.1, random_state=0).fit_transform(emb_pca50)
if viz == 15:
xy_umap, tempo_umap = xy, time.time() - inicio
desenha_projecao(ax, xy, f"UMAP, n_neighbors = {viz} ({time.time() - inicio:.1f} s)")
axes[0].legend(frameon=False, markerscale=2.5)
plt.tight_layout()
plt.show()
Besides looking, we can measure the quality of a map:
from sklearn.manifold import trustworthiness
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import balanced_accuracy_score
treino_t, teste_t = split_tile == "train", split_tile == "teste"
def knn_balanceado(X):
knn = KNeighborsClassifier(n_neighbors=5).fit(X[treino_t], classes_tile[treino_t])
return balanced_accuracy_score(classes_tile[teste_t], knn.predict(X[teste_t]))
mapas = {"PCA": (xy_pca, tempo_pca), "t-SNE": (xy_tsne, tempo_tsne), "UMAP": (xy_umap, tempo_umap)}
comparacao = pd.DataFrame({
nome: {"tempo (s)": tempo, "confiabilidade (10 vizinhos)": trustworthiness(emb_pca50, xy, n_neighbors=10),
"k-NN no mapa 2D (acurácia balanceada)": knn_balanceado(xy)}
for nome, (xy, tempo) in mapas.items()
}).T
comparacao.loc["sem reduzir (2.048 dimensões)", "k-NN no mapa 2D (acurácia balanceada)"] = knn_balanceado(embeddings.numpy())
fig, axes = plt.subplots(1, 3, figsize=(16, 5))
for ax, (nome, (xy, _)) in zip(axes, mapas.items()):
desenha_projecao(ax, xy, f"{nome} (trustworthiness = {comparacao.loc[nome, 'confiabilidade (10 vizinhos)']:.2f})")
axes[0].legend(frameon=False, markerscale=2.5)
plt.tight_layout()
plt.show()
comparacao.round(3).fillna("—")
| tempo (s) | confiabilidade (10 vizinhos) | k-NN no mapa 2D (acurácia balanceada) | |
|---|---|---|---|
| PCA | 0.185 | 0.849 | 0.581 |
| t-SNE | 1.672 | 0.983 | 0.756 |
| UMAP | 1.597 | 0.978 | 0.753 |
| sem reduzir (2.048 dimensões) | — | — | 0.772 |
Reading the results:
transform), so this number is a bit optimistic. With UMAP we could fit the map on the training points only and project the test points afterwards (exercise 3).| PCA | t-SNE | UMAP | |
|---|---|---|---|
| Type | linear | non-linear | non-linear |
| Preserves | global variance | local neighborhoods | local neighborhoods and part of the global structure |
| Speed | very fast | slow for many points | fast |
| Deterministic? | yes | no (depends on the seed) | no (depends on the seed) |
Projects new points (transform)? |
yes | no | yes |
| Do map distances mean anything? | yes (approximately) | not between groups | only approximately |
| Use for | preprocessing, compressing, interpreting | visualizing groups | visualizing groups, preprocessing for clustering |
A map only makes sense when we can see what each point represents. Below is an interactive map made with Bokeh, which works in Jupyter, in VS Code and also on the course’s published page (the interaction runs in the browser):
from bokeh.plotting import figure, show, output_notebook
from bokeh.models import ColumnDataSource, CustomJS, Div, HoverTool, RadioButtonGroup
from bokeh.layouts import column, row
output_notebook(hide_banner=True)
def miniatura(tile, lado=64):
"""Converts an image tile into an embedded JPEG thumbnail (data URI) for the browser to display."""
img = Image.fromarray((tile.permute(1, 2, 0).numpy() * 255).astype("uint8")).resize((lado, lado))
buffer = BytesIO()
img.save(buffer, format="JPEG", quality=70)
return "data:image/jpeg;base64," + base64.b64encode(buffer.getvalue()).decode()
fonte = ColumnDataSource(dict(
x=xy_umap[:, 0], y=xy_umap[:, 1],
x_umap=xy_umap[:, 0], y_umap=xy_umap[:, 1],
x_tsne=xy_tsne[:, 0], y_tsne=xy_tsne[:, 1],
x_pca=xy_pca[:, 0], y_pca=xy_pca[:, 1],
classe=[NOMES_LC[c] for c in classes_tile],
cor=[cores_pontos[c] for c in classes_tile],
foto=[i for i, _ in origem],
img=[miniatura(t) for t in tiles],
))
mapa = figure(width=620, height=560, tools="lasso_select,box_select,pan,wheel_zoom,reset",
active_drag="lasso_select", title="ResNet-50 embeddings (each point is an image tile)",
toolbar_location="above")
mapa.scatter("x", "y", source=fonte, size=6, color="cor", alpha=0.75, legend_field="classe",
selection_color="cor", nonselection_alpha=0.12)
mapa.add_tools(HoverTool(tooltips='<div><img src="@img" width="96" height="96"><br><b>@classe</b><br>@foto</div>'))
mapa.legend.location = "top_left"
mapa.xaxis.visible = mapa.yaxis.visible = False
mapa.grid.visible = False
painel = Div(text="<i>Draw a lasso around some points to see the images.</i>", width=430, height=560,
styles={"overflow-y": "auto"})
fonte.selected.js_on_change("indices", CustomJS(args=dict(fonte=fonte, painel=painel), code="""
const idx = fonte.selected.indices;
const d = fonte.data;
if (idx.length === 0) { painel.text = "<i>No points selected.</i>"; return; }
const contagem = {};
for (const i of idx) contagem[d.classe[i]] = (contagem[d.classe[i]] || 0) + 1;
let html = `<b>${idx.length} imagens selecionadas</b><br>`;
html += Object.entries(contagem).map(([c, n]) => `${c}: ${n} (${Math.round(100 * n / idx.length)}%)`).join(" · ");
html += `<div style="margin-top:6px">`;
for (const i of idx.slice(0, 120)) html += `<img src="${d.img[i]}" width="64" height="64" style="margin:1px" title="${d.classe[i]}">`;
if (idx.length > 120) html += `<br><i>... e mais ${idx.length - 120}</i>`;
painel.text = html + "</div>";
"""))
botoes = RadioButtonGroup(labels=["UMAP", "t-SNE", "PCA"], active=0)
botoes.js_on_change("active", CustomJS(args=dict(fonte=fonte), code="""
const chave = ["umap", "tsne", "pca"][this.active];
const d = fonte.data;
d.x = d["x_" + chave]; d.y = d["y_" + chave];
fonte.selected.indices = [];
fonte.change.emit();
"""))
show(column(botoes, row(mapa, painel)))Ideas for exploring:
For printing (or if the interactive map doesn’t show up), the same UMAP map with some of the images drawn on top:
fig, axes = plt.subplots(1, 2, figsize=(16, 7), width_ratios=[1, 1.15])
desenha_projecao(axes[0], xy_umap, "UMAP of the embeddings, colored by class")
axes[0].legend(frameon=False, markerscale=2.5)
gerador = np.random.default_rng(0)
meio = 0.03 * (xy_umap.max() - xy_umap.min()) # half the side of each thumbnail
axes[1].scatter(xy_umap[:, 0], xy_umap[:, 1], s=4, color="#e6e5e1")
for k in gerador.choice(len(tiles), 60, replace=False):
caixa = [xy_umap[k, 0] - meio, xy_umap[k, 0] + meio, xy_umap[k, 1] - meio, xy_umap[k, 1] + meio]
axes[1].imshow(tiles[k].permute(1, 2, 0), extent=caixa, zorder=3)
axes[1].set(title="The same map with some of the images", xticks=[], yticks=[],
xlim=(xy_umap[:, 0].min() - 2 * meio, xy_umap[:, 0].max() + 2 * meio),
ylim=(xy_umap[:, 1].min() - 2 * meio, xy_umap[:, 1].max() + 2 * meio))
axes[1].grid(False)
plt.tight_layout()
plt.show()
If similar images have nearby embeddings, we can search for similar images with a simple calculation. The most widely used measure is cosine similarity: the cosine of the angle between two vectors (1 = same direction, 0 = unrelated).
\[\text{sim}(a, b) = \frac{a \cdot b}{\|a\|\,\|b\|}\]
For each query image, we look for the 5 most similar among the tiles of other photos (so neighboring tiles from the same photo don’t count).
emb_norm = F.normalize(embeddings, dim=1) # unit-length vectors: the dot product becomes the cosine
similaridade = emb_norm @ emb_norm.T # (N, N): the similarity of each pair of tiles
foto = np.array([i for i, _ in origem])
consultas = [int(np.flatnonzero(classes_tile == c)[3]) for c in [3, 2, 0]] # water, forest, background
fig, axes = plt.subplots(len(consultas), 6, figsize=(14, 2.95 * len(consultas)))
for linha, q in enumerate(consultas):
s = similaridade[q].clone()
s[torch.tensor(foto == foto[q])] = -1 # ignore tiles from the same photo
vizinhos = s.topk(5).indices
axes[linha, 0].imshow(tiles[q].permute(1, 2, 0))
axes[linha, 0].set_title(f"query ({NOMES_LC[classes_tile[q]]})", color=TINTA, fontsize=10)
for k, v in enumerate(vizinhos):
axes[linha, k + 1].imshow(tiles[v].permute(1, 2, 0))
axes[linha, k + 1].set_title(f"sim = {s[v]:.2f}\n{NOMES_LC[classes_tile[v]]}", fontsize=9,
color=VERDE if classes_tile[v] == classes_tile[q] else LARANJA)
for ax in axes[linha]:
ax.axis("off")
plt.suptitle("Similarity search on the embeddings (green = same class as the query)", y=1.0)
plt.tight_layout()
plt.show()
With the similarity matrix of all pairs, we can compute the mean similarity between the tiles of each pair of classes. On the diagonal, the similarity within each class; off it, between classes.
nomes_presentes = [NOMES_LC[c] for c in classes_presentes]
media_sim = np.zeros((len(classes_presentes), len(classes_presentes)))
for a, ca in enumerate(classes_presentes):
for b, cb in enumerate(classes_presentes):
bloco = similaridade[np.ix_(classes_tile == ca, classes_tile == cb)]
if ca == cb: # within a class: ignore the diagonal (each tile with itself)
n = bloco.shape[0]
media_sim[a, b] = (bloco.sum() - n) / (n * (n - 1))
else:
media_sim[a, b] = bloco.mean()
fig, ax = plt.subplots(figsize=(5.5, 4.5))
im = ax.imshow(media_sim, cmap="Blues", vmin=0, vmax=1)
for a in range(len(classes_presentes)):
for b in range(len(classes_presentes)):
ax.text(b, a, f"{media_sim[a, b]:.2f}", ha="center", va="center", fontsize=12,
color="white" if media_sim[a, b] > 0.6 else TINTA)
ax.set(xticks=range(len(nomes_presentes)), xticklabels=nomes_presentes, yticks=range(len(nomes_presentes)),
yticklabels=nomes_presentes, title="Mean cosine similarity")
ax.grid(False)
plt.colorbar(im, ax=ax, shrink=0.8)
plt.show()
Reading the plot: the similarity within each class (diagonal) is higher than between classes, and that’s what makes similarity search and k-NN work. Forest is the most “homogeneous” class: tree canopies seen from above look very much alike. Background is the most varied, as we saw on the interactive map.
An embedding is also a great feature table for classic Machine Learning methods. With a simple k-nearest neighbors (k-NN) on the embeddings, without training the network, we classify the dominant class of the tiles from the test photos using only the tiles from the training photos:
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, balanced_accuracy_score
treino_t, teste_t = split_tile == "train", split_tile == "teste"
knn = KNeighborsClassifier(n_neighbors=5, metric="cosine").fit(embeddings[treino_t].numpy(), classes_tile[treino_t])
pred_knn = knn.predict(embeddings[teste_t].numpy())
maioria = np.bincount(classes_tile[treino_t]).argmax()
print(f"training tiles: {treino_t.sum()}, test tiles: {teste_t.sum()}")
print(f"k-NN on embeddings: accuracy = {accuracy_score(classes_tile[teste_t], pred_knn):.1%} "
f"balanced accuracy = {balanced_accuracy_score(classes_tile[teste_t], pred_knn):.1%}")
print(f"always guessing '{NOMES_LC[maioria]}': accuracy = {(classes_tile[teste_t] == maioria).mean():.1%}")pedaços de treino: 1023, de teste: 451
k-NN nos embeddings: acurácia = 87.1% acurácia balanceada = 78.5%
chutar sempre 'fundo': acurácia = 61.9%
Reading the results: without training the network and without any tuning, a k-NN on the embeddings does much better than always guessing the most common class. The balanced accuracy (the mean accuracy per class) shows that it also gets the smaller classes right, not just the background. That’s why embeddings from pre-trained models are so widely used: they turn images into feature tables ready for the classic methods from the Machine Learning classes.
The same idea is changing remote sensing: instead of downloading and processing raw images, you can now use ready-made embeddings, computed by foundation models. Examples:
With embeddings, tasks like “find areas similar to this one”, grouping regions or training a classifier with few examples become fast and cheap. In class 7 we saw that Transformers produce an embedding for each image patch: the PCA of DINOv2 features we did there was exactly a dimensionality reduction of embeddings, like the ones in this class.
| Method | Year | Idea | When to use |
|---|---|---|---|
| PCA | 1901 / 1933 | directions of greatest variance (linear) | compressing, removing noise, preprocessing, interpreting |
| t-SNE | 2008 | preserve neighborhoods (probabilities) | visualizing groups; don’t interpret distances between groups |
| UMAP | 2018 | preserve a neighbor graph | visualizing groups, projecting new points, preprocessing for clustering |
tiles.flatten(1)). Does k-NN get better or worse? What does that say about the embeddings?random_state). Do the groups move around? And what stays the same?transform to project the tiles from the test photos onto the map, fitting UMAP on the training tiles only. Do the test points land in the right groups?dino.forward_features(...)[:, 0], the [CLS] token) to generate the embeddings. Do the map and k-NN get better?