Mini Project: A Tiny 3D Renderer and Recommender
This project puts the course to work twice. In part 1 you project a rotating wireframe cube onto a screen using only matrices you write yourself. In part 2 you build a tiny movie recommender from a made-up ratings matrix with a truncated SVD. Both are small versions of what real graphics engines and recommendation systems do.
What we are building:
| Step | Part | New concepts |
|---|---|---|
| 1. The cube and its model matrix | renderer | homogeneous coordinates, rotation matrices, composition |
| 2. Camera and projection | renderer | look-at view matrix, perspective matrix, perspective divide, viewport |
| 3. Animate and draw | renderer | the full pipeline per frame, wireframe plot |
| 4. The ratings matrix | recommender | centring, low-rank structure, singular values |
| 5. Predict and recommend | recommender | truncated SVD, user and movie vectors, cosine similarity |
| 6. Does it generalize? | recommender | held-out ratings, RMSE against a baseline |
Note: Each step is a complete program (the playground does not share variables between runs), so the helper functions are repeated where needed.
Part 1: A tiny 3D renderer
Step 1: The cube and its model matrix
A cube is 8 corner points and 12 edges. Store the corners as homogeneous column vectors so that rotations and translations are all matrix products (Graphics Transforms). The model matrix spins the cube about , tilts it about and moves it, in that order: . Rotation matrices are orthogonal, so edge lengths must survive; check it.
import numpy as np
from itertools import product
V = np.array([[x, y, z, 1.0] for x, y, z in product([-1, 1], repeat=3)]).T # 4 x 8
E = [(i, j) for i in range(8) for j in range(i + 1, 8)
if np.sum(np.abs(V[:3, i] - V[:3, j])) == 2] # differ in one coord
def rot_x(deg):
c, s = np.cos(np.radians(deg)), np.sin(np.radians(deg))
return np.array([[1, 0, 0, 0], [0, c, -s, 0], [0, s, c, 0], [0, 0, 0, 1]])
def rot_y(deg):
c, s = np.cos(np.radians(deg)), np.sin(np.radians(deg))
return np.array([[c, 0, s, 0], [0, 1, 0, 0], [-s, 0, c, 0], [0, 0, 0, 1]])
def translate(x, y, z):
M = np.eye(4); M[:3, 3] = [x, y, z]; return M
M = translate(0, 0.5, 0) @ rot_x(20) @ rot_y(30)
W = M @ V
print("vertices:", V.shape[1], " edges:", len(E))
print("first corner in world space:", np.round(W[:3, 0], 4))
lengths = [np.linalg.norm(W[:3, i] - W[:3, j]) for i, j in E]
print("edge lengths after transform: min", round(min(lengths), 6), "max", round(max(lengths), 6))
print("rotation part orthogonal:", np.allclose(M[:3, :3].T @ M[:3, :3], np.eye(3)),
" det =", round(float(np.linalg.det(M[:3, :3])), 6))vertices: 8 edges: 12
first corner in world space: [-1.366 -0.3145 -0.686 ]
edge lengths after transform: min 2.0 max 2.0
rotation part orthogonal: True det = 1.0
Step 2: Camera and projection
The camera sits at (0, 1.5, 6) looking at the origin. The view matrix is the inverse of the camera's placement: its rotation part is the transpose of the camera basis (right, up, backward), because that basis is orthonormal. The perspective matrix puts into ; dividing by shrinks distant points. Finally the viewport maps NDC to pixels, flipping because screen rows grow downward.
import numpy as np
from itertools import product
V = np.array([[x, y, z, 1.0] for x, y, z in product([-1, 1], repeat=3)]).T
def look_at(eye, target, up=(0, 1, 0)):
eye, target, up = (np.asarray(a, float) for a in (eye, target, up))
b = (eye - target) / np.linalg.norm(eye - target)
r = np.cross(up, b); r /= np.linalg.norm(r)
u = np.cross(b, r)
view = np.eye(4); view[:3, :3] = np.vstack([r, u, b]); view[:3, 3] = -view[:3, :3] @ eye
return view
def perspective(fov, aspect, near, far):
f = 1 / np.tan(np.radians(fov) / 2)
return np.array([[f / aspect, 0, 0, 0], [0, f, 0, 0],
[0, 0, (far + near) / (near - far), 2 * far * near / (near - far)], [0, 0, -1, 0]])
def to_pixels(clip, width, height):
ndc = clip[:3] / clip[3]
return np.vstack([(ndc[0] + 1) / 2 * width, (1 - ndc[1]) / 2 * height]), ndc[2]
view = look_at((0, 1.5, 6), (0, 0, 0))
proj = perspective(50, 4 / 3, 0.1, 50)
print("camera at origin of view space:", np.round(view @ [0, 1.5, 6, 1], 6) + 0)
px, depth = to_pixels(proj @ view @ V, 640, 480)
for k in (0, 1, 6, 7):
print(f"corner {tuple(int(c) for c in V[:3, k])}: pixel ({px[0, k]:6.1f}, {px[1, k]:6.1f}) depth {depth[k]:.4f}")camera at origin of view space: [0. 0. 0. 1.]
corner (-1, -1, -1): pixel ( 250.4, 290.6) depth 0.9769
corner (-1, -1, 1): pixel ( 225.7, 354.4) depth 0.9673
corner (1, 1, -1): pixel ( 394.5, 149.7) depth 0.9750
corner (1, 1, 1): pixel ( 423.5, 164.7) depth 0.9637
The corners with are nearer the camera: they have smaller depth and are pushed further from the screen centre (320, 240), which is what perspective looks like.
Step 3: Animate and draw
Now run the whole pipeline, , for four rotation angles and draw the 12 edges of each frame. Nothing here is special to cubes: any mesh is vertices plus edges (or triangles), and a GPU runs exactly this multiplication in its vertex shader.
import numpy as np
import matplotlib.pyplot as plt
from itertools import product
V = np.array([[x, y, z, 1.0] for x, y, z in product([-1, 1], repeat=3)]).T
E = [(i, j) for i in range(8) for j in range(i + 1, 8) if np.sum(np.abs(V[:3, i] - V[:3, j])) == 2]
def rot_x(d):
c, s = np.cos(np.radians(d)), np.sin(np.radians(d))
return np.array([[1, 0, 0, 0], [0, c, -s, 0], [0, s, c, 0], [0, 0, 0, 1]])
def rot_y(d):
c, s = np.cos(np.radians(d)), np.sin(np.radians(d))
return np.array([[c, 0, s, 0], [0, 1, 0, 0], [-s, 0, c, 0], [0, 0, 0, 1]])
def look_at(eye, target, up=(0, 1, 0)):
eye, target, up = (np.asarray(a, float) for a in (eye, target, up))
b = (eye - target) / np.linalg.norm(eye - target)
r = np.cross(up, b); r /= np.linalg.norm(r); u = np.cross(b, r)
view = np.eye(4); view[:3, :3] = np.vstack([r, u, b]); view[:3, 3] = -view[:3, :3] @ eye
return view
def perspective(fov, aspect, near, far):
f = 1 / np.tan(np.radians(fov) / 2)
return np.array([[f / aspect, 0, 0, 0], [0, f, 0, 0],
[0, 0, (far + near) / (near - far), 2 * far * near / (near - far)], [0, 0, -1, 0]])
W_, H_ = 640, 480
PV = perspective(50, W_ / H_, 0.1, 50) @ look_at((0, 1.5, 6), (0, 0, 0)) # once per frame
fig, axes = plt.subplots(1, 4, figsize=(11, 2.8))
for ax, angle in zip(axes, (0, 30, 60, 90)):
clip = PV @ rot_x(20) @ rot_y(angle) @ V # P V M v
px = np.vstack([(clip[0] / clip[3] + 1) / 2 * W_, (1 - clip[1] / clip[3]) / 2 * H_])
for i, j in E:
ax.plot(px[0, [i, j]], px[1, [i, j]], "k-", lw=1)
ax.set_xlim(0, W_); ax.set_ylim(H_, 0); ax.set_aspect("equal"); ax.set_title(f"{angle}°")
ax.set_xticks([]); ax.set_yticks([])
w, h = np.ptp(px[0]), np.ptp(px[1])
print(f"angle {angle:2d}°: screen bounding box {w:5.1f} x {h:5.1f} px")angle 0°: screen bounding box 214.6 x 231.5 px
angle 30°: screen bounding box 250.7 x 267.5 px
angle 60°: screen bounding box 250.7 x 267.5 px
angle 90°: screen bounding box 214.6 x 231.5 px
The 0° and 90° frames have the same size, as do 30° and 60°: a cube rotated 90° about its own axis looks the same, and 30° and 60° are mirror images. Symmetry checks like this are a cheap way to catch matrix-order bugs.
Part 2: A tiny movie recommender
Step 4: The ratings matrix
Eight users have rated some of six movies on a 1–5 scale; 0 means "not rated". The data is made up, with two hidden tastes: action fans and drama fans. To expose taste rather than generosity, subtract each user's mean rating from their known ratings and leave the unknown ones at 0 (the neutral value after centring). Then look at the singular values (SVD).
import numpy as np
movies = ["Laser Raid", "Turbo Chase", "Iron Fist", "Quiet Lake", "Old Letters", "Rain Song"]
R = np.array([[5, 4, 5, 1, 0, 1],
[4, 5, 0, 2, 1, 1],
[5, 5, 4, 0, 1, 2],
[1, 2, 1, 5, 4, 0],
[0, 1, 2, 4, 5, 5],
[2, 1, 1, 5, 0, 4],
[4, 0, 5, 1, 2, 1],
[1, 1, 0, 4, 5, 4]], dtype=float)
known = R > 0
means = np.array([R[u, known[u]].mean() for u in range(len(R))])
C = np.where(known, R - means[:, None], 0.0)
U, s, Vt = np.linalg.svd(C, full_matrices=False)
print("ratings known:", int(known.sum()), "of", R.size)
print("user means:", np.round(means, 2))
print("singular values:", np.round(s, 3))
print("energy in top 1, 2 components:", np.round(np.cumsum(s**2)[:2] / np.sum(s**2), 3))ratings known: 40 of 48
user means: [3.2 2.6 3.4 2.6 3.4 2.6 2.6 3. ]
singular values: [9.042 4.116 2.337 1.761 1.656 0. ]
energy in top 1, 2 components: [0.743 0.897]
Two singular values stand out and together hold about 90% of the energy: the main pattern is "action versus drama", and a second one adds detail. We will keep .
Step 5: Predict and recommend
Keep the top singular triplets: (Low-Rank Approximation). Filling the unknown entries with 0 pulls every prediction toward the user's mean, so we use a classic refinement, iterative SVD imputation: replace the unknown entries by the current rank- prediction, recompute the SVD, and repeat. The known entries never change; only the guesses for the missing ones improve.
Row of is then a -dimensional user vector, column of is a movie vector, and a predicted rating is the user's mean plus their dot product. Movie vectors also give "fans of this also like" via cosine similarity.
import numpy as np
movies = ["Laser Raid", "Turbo Chase", "Iron Fist", "Quiet Lake", "Old Letters", "Rain Song"]
R = np.array([[5, 4, 5, 1, 0, 1], [4, 5, 0, 2, 1, 1], [5, 5, 4, 0, 1, 2], [1, 2, 1, 5, 4, 0],
[0, 1, 2, 4, 5, 5], [2, 1, 1, 5, 0, 4], [4, 0, 5, 1, 2, 1], [1, 1, 0, 4, 5, 4]], dtype=float)
def fit(R, k, iters=50):
known = R > 0
means = np.array([R[u, known[u]].mean() for u in range(len(R))])
C = np.where(known, R - means[:, None], 0.0)
X = C.copy()
for _ in range(iters):
U, s, Vt = np.linalg.svd(X, full_matrices=False)
L = (U[:, :k] * s[:k]) @ Vt[:k] # best rank-k approximation of X
X = np.where(known, C, L) # keep known entries, update the guesses
return means, U[:, :k] * s[:k], Vt[:k].T
means, users, items = fit(R, k=2)
pred = np.clip(means[:, None] + users @ items.T, 1, 5)
for u, i in zip(*np.where(R == 0)):
print(f"user {u} (mean {means[u]:.1f}): predicted {pred[u, i]:.2f} for {movies[i]}")
unit = items / np.linalg.norm(items, axis=1, keepdims=True)
sim = unit @ unit.T
for i in (0, 3):
j = max((j for j in range(len(movies)) if j != i), key=lambda j: sim[i, j])
print(f"fans of {movies[i]} also like {movies[j]} (cosine {sim[i, j]:.3f})")user 0 (mean 3.2): predicted 2.00 for Old Letters
user 1 (mean 2.6): predicted 3.53 for Iron Fist
user 2 (mean 3.4): predicted 2.93 for Quiet Lake
user 3 (mean 2.6): predicted 4.42 for Rain Song
user 4 (mean 3.4): predicted 1.64 for Laser Raid
user 5 (mean 2.6): predicted 3.68 for Old Letters
user 6 (mean 2.6): predicted 3.30 for Turbo Chase
user 7 (mean 3.0): predicted 1.92 for Iron Fist
fans of Laser Raid also like Turbo Chase (cosine 0.825)
fans of Quiet Lake also like Rain Song (cosine 0.758)
Every prediction follows the user's taste: action fans (users 0, 1, 2, 6) are predicted above their mean for action films and below it for dramas, and drama fans the reverse. The movie vectors cluster the same way, without the program ever being told which film is which genre.
Step 6: Does it generalize?
Predicting ratings the model was trained on proves nothing. Hide some known ratings, train on the rest, and compare the error on the hidden ones with a baseline that predicts each user's mean. Root mean squared error, , is the usual score.
import numpy as np
R = np.array([[5, 4, 5, 1, 0, 1], [4, 5, 0, 2, 1, 1], [5, 5, 4, 0, 1, 2], [1, 2, 1, 5, 4, 0],
[0, 1, 2, 4, 5, 5], [2, 1, 1, 5, 0, 4], [4, 0, 5, 1, 2, 1], [1, 1, 0, 4, 5, 4]], dtype=float)
def fit(R, k, iters=50):
known = R > 0
means = np.array([R[u, known[u]].mean() for u in range(len(R))])
C = np.where(known, R - means[:, None], 0.0)
X = C.copy()
for _ in range(iters):
U, s, Vt = np.linalg.svd(X, full_matrices=False)
L = (U[:, :k] * s[:k]) @ Vt[:k]
X = np.where(known, C, L)
return np.clip(means[:, None] + L, 1, 5), means
hidden = [(0, 2), (1, 0), (3, 4), (4, 3), (5, 5), (6, 0), (7, 4), (2, 1)] # known ratings we hide
train = R.copy()
for u, i in hidden:
train[u, i] = 0
truth = np.array([R[u, i] for u, i in hidden])
rmse = lambda guess: np.sqrt(np.mean((guess - truth) ** 2))
_, means = fit(train, 1, iters=1)
print(f"baseline (user mean) RMSE: {rmse(np.array([means[u] for u, i in hidden])):.3f}")
for k in (1, 2, 3, 4):
P, _ = fit(train, k)
print(f"SVD k={k}: RMSE {rmse(np.array([P[u, i] for u, i in hidden])):.3f}")baseline (user mean) RMSE: 1.875
SVD k=1: RMSE 0.706
SVD k=2: RMSE 1.691
SVD k=3: RMSE 1.443
SVD k=4: RMSE 1.852
The rank-1 model cuts the baseline's error by more than half: the single "action versus drama" direction is real signal. With only 32 training ratings, higher ranks fit noise instead (the errors jump around and get worse), the bias–variance trade-off in linear-algebra form: the low-rank constraint is what lets the model generalize. So hold-out testing, not the training fit, is how should be chosen; here it says rather than the we picked by eye in step 5.
Tip: Real recommenders (Netflix-prize style) do not fill missing entries with zeros. They fit and only on known ratings, with regularization, by alternating least squares or gradient descent. The SVD version here is the clean starting point those methods build on.
Where to go next
- Add back-face culling to the renderer: a triangle faces away from the camera when the 2D cross product of its projected edges is negative (Determinants).
- Replace the Euler-angle model matrix with a quaternion and slerp between two orientations (Rotations: Matrices vs Quaternions).
- Fit the recommender by least squares on known entries only (alternating least squares) and compare RMSE.
- Turn the movie vectors into a 2D map with PCA and plot it.
Test yourself
In , why is computed once per frame rather than once per vertex?
- Because is the same for every object and vertex in that frame
- Because matrix multiplication is commutative
- Because is always the identity
- It must be recomputed per vertex
In the recommender, what does a user's -dimensional vector represent?
- Their average rating
- Their position in the space of hidden taste factors
- The number of movies they rated
- Their user id
Why did a larger make the held-out error worse?
- The SVD becomes inaccurate
- Extra components fit noise in the small training set instead of real patterns
- Ratings must be integers
- must equal the number of users