Skip to content

Fashion-MNIST

Terminal window
python examples/fashion_mnist.py

examples/fashion_mnist.py fits FloDR to the 60,000 Fashion-MNIST training images, as 50 standardised principal components of the pixels, and treats the 10,000 test images as new points. It needs only FloDR, downloads the images from OpenML on the first run and takes about four minutes with a GPU.

transform: 10000 images in 4 ms, 76.8% agree
transform_opt: 10000 images in 2757 ms, 82.7% agree
log density median -77.1, coverage: certified

60,000 Fashion-MNIST images on a FloDR map, and images decoded on a grid over it

The map, and images decoded on a grid over it with the residual of the training images nearest each grid point (the inverse). Each image takes the colour of the class nearest it.

10,000 Fashion-MNIST test images placed by transform and by transform_opt

The test images placed by transform and by transform_opt (new points).

Two walks across the Fashion-MNIST map, decoded at nine steps

Walks between the densest points of two classes, decoded at nine steps, faded where no training image is near.

Fashion-MNIST test images coloured by their log density, with the most and the least likely

The test images by their log density, and the most and the least likely (density).

The script

import time
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.lines import Line2D
from scipy.sparse.csgraph import dijkstra
from scipy.spatial import cKDTree
from sklearn.datasets import fetch_openml
from sklearn.decomposition import PCA
from sklearn.neighbors import kneighbors_graph
from flodr import FloDR, viz
OUT = Path(__file__).resolve().parents[1] / "docs" / "docs" / "images"
CLASSES = ["T-shirt", "Trouser", "Pullover", "Dress", "Coat"]
CLASSES += ["Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"]
ROUTES = [("Sandal", "Sneaker"), ("T-shirt", "Dress")]
# the 60,000 training and 10,000 test images as 50 standardised principal components
pixels, y = fetch_openml(
"Fashion-MNIST", version=1, return_X_y=True, as_frame=False, parser="liac-arff"
)
y = y.astype(int)
labels = np.array(CLASSES)[y]
train, test = np.arange(60000), np.arange(60000, 70000)
pca = PCA(50, random_state=0).fit(pixels[train])
P = pca.transform(pixels)
mean, sd = P[train].mean(0), P[train].std(0)
X = ((P - mean) / sd).astype(np.float32)
model = FloDR(random_state=0).fit(X[train])
Y = model.embedding_
latent = model.transform_latent(X[train])
tree = cKDTree(Y)
pal = viz.palette(labels)
handles = [
Line2D([], [], ls="", marker="o", ms=5, c=c, label=t) for t, c in pal.items()
]
box = dict(boxstyle="round,pad=0.2", fc="white", ec="none", alpha=0.85)
plt.rcParams.update(viz.RC)
def decode(positions):
# each position with the residual of the 15 training images nearest it on the map
nn = tree.query(positions, k=15)[1]
Z = latent[nn].mean(1)
Z[:, :2] = positions
x = pca.inverse_transform(model.inverse_latent(Z) * sd + mean)
return np.clip(x / 255, 0, 1).reshape(-1, 28, 28), labels[train][nn[:, 0]]
def tile(ax, img, xy, half, colour, alpha=1.0):
# an image in the colour of its class, ink as opacity
rgba = np.zeros((28, 28, 4))
rgba[..., :3], rgba[..., 3] = colour, alpha * img / max(img.max(), 1e-6)
x, y = xy
ax.imshow(rgba, extent=(x - half, x + half, y - half, y + half), zorder=3)
# the map, and images decoded on a grid over it wherever training images are near
fig, (a, b) = plt.subplots(1, 2, figsize=(8.5, 4.8))
fig.subplots_adjust(left=0.01, right=0.99, top=0.93, bottom=0.08, wspace=0.04)
viz.plot_embedding(Y, labels[train], ax=a, colours=pal)
viz.frame(b, Y)
(x0, x1), (y0, y1), n = b.get_xlim(), b.get_ylim(), 22
step = (x1 - x0) / n
gx, gy = np.meshgrid(x0 + step * (np.arange(n) + 0.5), y0 + step * (np.arange(n) + 0.5))
grid = np.c_[gx.ravel(), gy.ravel()].astype(np.float32)
grid = grid[tree.query(grid)[0] < 0.5 * step]
for img, c, xy in zip(*decode(grid), grid):
tile(b, img, xy, 0.48 * step, pal[c])
viz.frame(b, Y)
a.set_title("60,000 Fashion-MNIST images")
b.set_title("decoded from the map")
fig.legend(
handles=handles,
loc="upper center",
bbox_to_anchor=(0.5, 0.08),
ncol=5,
frameon=False,
)
viz.save(fig, OUT / "fashion_map.png", dpi=200)
# new images, one forward pass each or optimised against the training map, scored by the
# labels of their 15 nearest training images on the map
placed = {}
fig, axes = plt.subplots(1, 2, figsize=(8.5, 4.5))
fig.subplots_adjust(left=0.01, right=0.99, top=0.92, bottom=0.01, wspace=0.04)
for ax, place in zip(axes, (model.transform, model.transform_opt)):
place(X[test[:100]])
t = time.perf_counter()
Y_new = placed[place.__name__] = place(X[test])
ms = 1e3 * (time.perf_counter() - t)
votes = y[train][tree.query(Y_new, k=15)[1]]
agree = np.mean(np.array([np.bincount(v).argmax() for v in votes]) == y[test])
print(f"{place.__name__}: {len(test)} images in {ms:.0f} ms, {agree:.1%} agree")
ax.scatter(*Y.T, s=0.3, c="0.85", lw=0, rasterized=True)
viz.plot_embedding(Y_new, labels[test], ax=ax, colours=pal, s=1)
viz.frame(ax, Y)
ax.set_title(f"{place.__name__}, {ms:,.0f} ms")
text = f"{agree:.0%} among their own class"
ax.text(0.03, 0.03, text, transform=ax.transAxes, fontsize=9, bbox=box)
Y_test = placed["transform"]
viz.save(fig, OUT / "fashion_new_points.png", dpi=200)
def mode(c):
# the image of class c with the most images of its class close by on the map
Q = Y[labels[train] == c]
return Q[cKDTree(Q).query(Q, 50)[0][:, -1].argmin()]
def route(a, b, n=160):
# the shortest walk between the modes of two classes through the map's graph of 15
# nearest neighbours, so it stays on the data, at equal arc length
i, j = tree.query([mode(a), mode(b)])[1]
pred = dijkstra(graph, directed=False, indices=j, return_predecessors=True)[1]
walk = [i]
while walk[-1] != j:
walk.append(pred[walk[-1]])
Q = Y[walk]
s = np.r_[0, np.cumsum(np.linalg.norm(np.diff(Q, axis=0), axis=1))]
t = np.linspace(0, s[-1], n)
return np.stack([np.interp(t, s, Q[:, j]) for j in (0, 1)], 1).astype(np.float32)
# walks across the map, decoded at nine steps; faded where no training image is near
graph = kneighbors_graph(Y, 15, mode="distance")
paths = [route(*r) for r in ROUTES]
gap = np.percentile(tree.query(Y, k=2)[0][:, 1], 99)
far = [tree.query(p)[0] > gap for p in paths]
ends = [((a, pal[a]), (b, pal[b])) for a, b in ROUTES]
on = np.isin(labels[train], sum(ROUTES, ()))
fig = plt.figure(figsize=(8.5, 3.0))
gs = fig.add_gridspec(1, 2, width_ratios=(1, 1.7), wspace=0.05)
ax = fig.add_subplot(gs[0])
viz.plot_paths(Y, paths, labels[train], pal, ends, far, on, ax)
strips = fig.add_subplot(gs[1])
for p, (path, (a, b)) in enumerate(zip(paths, ROUTES)):
k = np.linspace(0, len(path) - 1, 9).round().astype(int)
ax.scatter(*path[k].T, s=14, fc="w", ec="k", lw=0.8, zorder=6)
for i, (img, c) in enumerate(zip(*decode(path[k]))):
x, y0 = 1.1 * i, -1.7 * p
tile(strips, img, (x, y0), 0.5, pal[c], 0.35 if far[p][k[i]] else 1.0)
edge = plt.Rectangle((x - 0.5, y0 - 0.5), 1, 1, fc="none", ec="0.85", lw=0.6)
strips.add_patch(edge)
strips.text(-0.5, -1.7 * p + 0.62, f"{a} to {b}", fontsize=10)
strips.set(xlim=(-0.55, 9.35), ylim=(-1.7 * len(ROUTES) + 1.15, 1.0), aspect="equal")
strips.axis("off")
viz.save(fig, OUT / "fashion_paths.png", dpi=200)
# the density of the test images: the map coloured by log p(x), and the most and the
# least likely images
logp = model.score_samples(X[test])
order = np.argsort(logp)
cert = model.coverage_certificate(X[test])
print(f"log density median {np.median(logp):.1f}, coverage: {cert['certifies']}")
fig = plt.figure(figsize=(8.5, 3.6))
gs = fig.add_gridspec(1, 2, width_ratios=(1, 1.1), wspace=0.3)
ax = fig.add_subplot(gs[0])
norm = plt.Normalize(*np.percentile(logp, [2, 98]))
viz.plot_embedding(Y_test, values=logp, ax=ax, cmap="magma", norm=norm, order="high")
fig.colorbar(plt.cm.ScalarMappable(norm, "magma"), ax=ax, shrink=0.7, label="log p(x)")
ax.set_title("test images by their log density")
grid = gs[1].subgridspec(4, 6, hspace=0.12, wspace=0.06)
for r, (idx, name) in enumerate(
((order[::-1], "most likely"), (order, "least likely"))
):
for i, j in enumerate(idx[:12]):
a = fig.add_subplot(grid[2 * r + i // 6, i % 6])
a.imshow(pixels[test[j]].reshape(28, 28), cmap="gray_r")
a.set(xticks=[], yticks=[])
a.spines[:].set_color("0.85")
if i == 0:
a.set_title(name, loc="left", fontsize=10)
viz.save(fig, OUT / "fashion_density.png", dpi=200)