import base64
import io
from pathlib import Path
import numpy as np
import plotly.graph_objects as go
from PIL import Image
from plotly.subplots import make_subplots
from scipy.sparse.csgraph import shortest_path
from sklearn.manifold import SpectralEmbedding
from sklearn.neighbors import kneighbors_graphTwenty Objects on a Turntable
Math 123: Mathematical Aspects of Data Analysis — Fall 2026
In 1996, researchers at Columbia put twenty small objects, one at a time, on a motorized turntable and photographed each one every \(5^\circ\) as it turned (Nene et al. 1996). The result, the Columbia Object Image Library (COIL-20), is \(20\times72=1440\) greyscale photographs.
We will start with one object: the duck. Suppose we give a computer its \(72\) photographs, shuffled, with no angles attached. Can an embedding reveal that these pictures came from something turning?
The data
Each photograph is \(128\times128\) pixels with brightness between \(0\) and \(1\). To keep things fast we average each \(4\times4\) block of pixels, which leaves \(32\times32\) images, so each photograph becomes a vector in \(\Rbb^{1024}\). We keep higher-resolution copies for display.
DATA = Path("coil-20-proc")
n_pose = 72
angle = 5 * np.arange(n_pose) # held aside until we visualize the embeddings
photos = np.array([
np.asarray(Image.open(DATA / f"obj1__{p}.png"), dtype=float) / 255
for p in range(n_pose)
])
def shrink(images, f):
"""Average each f x f block of pixels."""
*lead, h, w = images.shape
return images.reshape(*lead, h // f, f, w // f, f).mean(axis=(-3, -1))
X = shrink(photos, 4).reshape(n_pose, -1) # 72 photographs, 1024 pixels each
thumbs = shrink(photos, 2) # 64 x 64 copies for the embedding plotsFigure style and image helpers
# The same muted palette as the other examples, which reads correctly against
# both the light and the dark version of this site.
INK = "#7c7c78"
GRID = "rgba(128, 128, 128, 0.28)"
CYCLIC = "Phase" # a colorscale that wraps around, like an angle
def style(fig, height, title=None):
fig.update_annotations(font=dict(color=INK, size=13))
fig.update_layout(template="simple_white", paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)", font=dict(color=INK, size=13),
title=dict(text=title, x=0, xanchor="left", font=dict(size=15)),
height=height, margin=dict(l=20, r=20, t=70 if title else 50, b=20),
hovermode="closest")
return fig
def bare_axes(fig, n_panels):
"""Equal scales on both axes of every panel, and no ticks: only shapes matter."""
for i in range(1, n_panels + 1):
suffix = "" if i == 1 else str(i)
fig.layout[f"yaxis{suffix}"].scaleanchor = f"x{suffix}"
fig.layout[f"xaxis{suffix}"].constrain = "domain"
fig.update_xaxes(showticklabels=False, ticks="", showgrid=False, zeroline=False, linecolor=GRID)
fig.update_yaxes(showticklabels=False, ticks="", showgrid=False, zeroline=False, linecolor=GRID)
def png_uri(image):
"""Encode a greyscale image in [0, 1] as a PNG data URI."""
buffer = io.BytesIO()
Image.fromarray((255 * np.clip(image, 0, 1)).astype(np.uint8), "L").save(buffer, "PNG")
return "data:image/png;base64," + base64.b64encode(buffer.getvalue()).decode()
def add_thumbs(fig, Y, idx, images, size, row=None, col=None, push=1.0):
"""Put small photos at the points Y[idx], pushed away from the centre by the factor push."""
centre = Y.mean(axis=0)
for i in idx:
x, y = centre + push * (Y[i] - centre)
fig.add_layout_image(source=png_uri(images[i]), x=x, y=y, sizex=size, sizey=size,
xanchor="center", yanchor="middle", layer="above",
xref="x", yref="y", row=row, col=col)Animate the duck turning
# Repeat the first view at the end to complete the turn.
frames = [go.Frame(name=str(p), data=[go.Image(
source=png_uri(photos[p % n_pose]), hoverinfo="skip")])
for p in range(n_pose + 1)]
fig = go.Figure(data=frames[0].data, frames=frames)
fig.update_xaxes(visible=False, range=[-0.5, 127.5], fixedrange=True,
constrain="domain")
fig.update_yaxes(visible=False, range=[127.5, -0.5], scaleanchor="x", fixedrange=True)
style(fig, 380)
fig.update_layout(
margin=dict(l=0, r=0, t=0, b=60),
hovermode=False,
updatemenus=[dict(
type="buttons", direction="left", x=0.5, y=-0.04,
xanchor="center", yanchor="top", showactive=False,
bgcolor="rgba(0,0,0,0)", borderwidth=0,
font=dict(color=INK, size=13), pad=dict(t=8, b=0, l=0, r=0),
buttons=[
dict(label="▶ Play", method="animate", args=[None, dict(
frame=dict(duration=80, redraw=True), transition=dict(duration=0),
fromcurrent=True, mode="immediate")]),
dict(label="Ⅱ Pause", method="animate", args=[[None], dict(
frame=dict(duration=0, redraw=False), transition=dict(duration=0),
mode="immediate")]),
],
)],
)
fig.show(auto_play=False, config=dict(displayModeBar=False, responsive=True))One object is a loop
Think about what the \(72\) photographs of the duck look like as points in \(\Rbb^{1024}\). Turning the duck a little changes each pixel a little, so photographs taken \(5^\circ\) apart are close together. After a full turn the duck is back where it started. So the \(72\) points should lie along a closed curve in \(\Rbb^{1024}\): a loop, with one degree of freedom, the angle. We shuffle the photographs before embedding them; the methods receive only the pixel values.
Three pictures of the duck
Now we ask for coordinates in the plane, in three ways.
- PCA projects the centered photos onto their top two principal directions.
- The Laplacian eigenmap keeps two eigenvectors of the normalized Laplacian of the \(4\)-nearest-neighbour graph.
- Isomap measures distances along the same graph and runs classical MDS.
def classical_mds(delta, m):
n = len(delta)
J = np.eye(n) - np.ones((n, n)) / n
B = -0.5 * J @ (delta**2) @ J
lam, Q = np.linalg.eigh(B) # increasing order
lam, Q = lam[::-1], Q[:, ::-1] # decreasing order
return Q[:, :m] * np.sqrt(lam[:m]) # Y = Q_m Lambda_m^{1/2}
def isomap(x, m, k=K):
G = kneighbors_graph(x, k, mode="distance") # edge lengths
delta = shortest_path(G, method="D", directed=False) # Dijkstra
return classical_mds(delta, m)
def pca(x, m):
xc = x - x.mean(axis=0)
_, _, Vt = np.linalg.svd(xc, full_matrices=False)
return xc @ Vt[:m].T
def eigenmap(x, m, k=K):
G = kneighbors_graph(x, k)
W = 0.5 * (G + G.T)
return SpectralEmbedding(n_components=m, affinity="precomputed",
random_state=0).fit_transform(W)
duck = {"PCA": pca(x_duck, 2), "Laplacian eigenmap": eigenmap(x_duck, 2)}
duck["Isomap"] = isomap(x_duck, 2)None of the three methods saw the angles. In the pictures below we use them only afterwards, to color each point and to draw a thin line joining photos taken \(5^\circ\) apart.
Helper for plotting loops
def loop_figure(panels, theta, images, title, every=9, upto=360, push=1.45, height=470):
"""Side-by-side embeddings, colored by angle, with photos (taken before `upto` degrees) around each loop."""
fig = make_subplots(rows=1, cols=len(panels), subplot_titles=[f"<b>{t}</b>" for t in panels],
horizontal_spacing=0.04)
order = np.argsort(theta)
for col, Y in enumerate(panels.values(), start=1):
Y = Y / np.abs(Y - Y.mean(axis=0)).max() # same size in every panel
ring = np.r_[order, order[:1]] # close the loop
fig.add_trace(go.Scatter(x=Y[ring, 0], y=Y[ring, 1], mode="lines", hoverinfo="skip",
line=dict(color=GRID, width=1), showlegend=False), row=1, col=col)
fig.add_trace(go.Scatter(
x=Y[:, 0], y=Y[:, 1], mode="markers", showlegend=False,
marker=dict(size=8, color=theta, colorscale=CYCLIC, cmin=0, cmax=360,
showscale=(col == len(panels)),
colorbar=dict(title="angle", ticksuffix="°", thickness=12, len=0.8)),
customdata=theta, hovertemplate="%{customdata}°<extra></extra>"), row=1, col=col)
shown = [i for i in order[::every] if theta[i] < upto]
add_thumbs(fig, Y, shown, images, size=0.42, row=1, col=col, push=push)
lim = push + 0.4
fig.update_xaxes(range=[Y[:, 0].mean() - lim, Y[:, 0].mean() + lim], row=1, col=col)
fig.update_yaxes(range=[Y[:, 1].mean() - lim, Y[:, 1].mean() + lim], row=1, col=col)
bare_axes(fig, len(panels))
return style(fig, height, title)Plot the three embeddings
PCA projects onto the best-fitting plane, but here the projected loop folds back on itself: photographs from quite different views land close together. The eigenmap and Isomap arrange the photographs around a circle in rotation order. Follow the pictures around either circle and the duck turns through one full rotation. The embedding has revealed the rotation using only similarities between photographs.
A loop that goes around twice
The duck looks different from every side, so each photograph pins down the angle. Not every object is like that. Here is object \(19\) in the library, a toy car.
Show views half a turn apart
shown = [0, 9, 18, 27] # 0, 45, 90, 135 degrees
fig = make_subplots(rows=2, cols=4, vertical_spacing=0.1, horizontal_spacing=0.02,
subplot_titles=[f"{angle[p] + 180 * r}°" for r in range(2) for p in shown])
for r in range(2):
for c, p in enumerate(shown):
fig.add_trace(go.Image(source=png_uri(car_photos[(p + 36 * r) % n_pose]), hoverinfo="skip"),
row=r + 1, col=c + 1)
fig.update_xaxes(visible=False)
fig.update_yaxes(visible=False)
style(fig, 380).update_layout(margin=dict(l=0, r=0, t=30, b=0), hovermode=False)
fig.show(config=dict(displayModeBar=False, responsive=True))A car seen from its left side and from its right side has nearly the same outline, and so do its front and its back. The pixels agree. Below is the average distance in \(\Rbb^{1024}\) between two photographs taken a given angle apart, together with how many edges of the \(4\)-nearest-neighbour graph join photographs more than \(90^\circ\) apart.
def mean_distance(x, degrees):
"""Average distance between photographs taken `degrees` apart."""
return np.linalg.norm(x - np.roll(x, -degrees // 5, axis=0), axis=1).mean()
def far_edges(x, k=K):
"""Count the edges of the k-nearest-neighbour graph joining photos more than 90 degrees apart."""
G = kneighbors_graph(x, k)
i, j = np.triu((G + G.T).toarray()).nonzero()
gap = np.abs(angle[i] - angle[j])
gap = np.minimum(gap, 360 - gap)
return f"{(gap > 90).sum()} of {len(i)}"
print("apart duck car")
for degrees in [5, 10, 90, 180]:
print(f"{degrees:>4}° {mean_distance(X, degrees):6.2f} {mean_distance(X_car, degrees):5.2f}")
print(f"\nedges joining photos more than 90° apart: duck {far_edges(X)}, car {far_edges(X_car)}")apart duck car
5° 1.98 2.84
10° 3.45 4.52
90° 10.83 11.14
180° 11.62 3.21
edges joining photos more than 90° apart: duck 0 of 149, car 74 of 156
For the duck, photographs taken farther apart are farther apart in \(\Rbb^{1024}\). For the car, the photograph taken half a turn later is about as close as the one taken \(5^\circ\) later, and closer than the one taken \(10^\circ\) later. So nearly half of the edges in the car’s graph join a view to its opposite. Here are the same three embeddings of the shuffled car photographs.
Plot the three embeddings
All three methods find a loop, and without the colors we would happily conclude that the car turned once. The colors say otherwise. Going once around any of these loops is only half a turn of the turntable; the second half of the turn retraces the first, and each point sits next to the photograph taken \(180^\circ\) away. Hover over neighbouring points to check.
Nothing has gone wrong. The methods only see distances between photographs, and to the pixels the angles \(\theta\) and \(\theta+180^\circ\) give nearly the same view. So the data really do lie along a loop, but the loop is parametrized by the angle modulo \(180^\circ\), and the embeddings draw that loop faithfully. An embedding recovers the shape of the data, which need not be the shape of the motion that produced it. If two states of a system look alike, no method that sees only the pictures can tell them apart.