CNN vs Recurrent Models, Plus From-Scratch K-Means
Machine LearningModel answerLast updated
Compare convolutional and recurrent architectures, derive LSTM gating and tensor shapes, then implement and analyze a vectorized K-means with k-means++ seeding.
This is a two-part question on representation learning and unsupervised clustering.
Part A — Architectures. For a 224×224 RGB image and for variable-length text, compare convolutional networks (CNNs) with recurrent networks (RNNs). Cover:
- Inductive biases: spatial locality and translation equivariance for images; ordering and sequential state for text.
- Parameter sharing and receptive-field growth.
- Ability to capture long-range dependencies and how much sequential (time-step) computation each requires.
- Situations where a 1D CNN (optionally dilated/causal) can substitute for an RNN or a Transformer.
Then treat LSTMs specifically: write the equations for the input, forget, output, and candidate gates; explain how the cell-state pathway reduces vanishing gradients compared with a vanilla RNN; and report output and final hidden/cell-state shapes for an input of shape (batch=32, seq_len=100, feat=64) with hidden size 128, for both a one-layer unidirectional and a one-layer bidirectional model.
Part B — Clustering. Implement K-means from scratch in Python/NumPy with:
- k-means++ initialization,
- vectorized assignment and centroid-update steps,
- stopping when the within-cluster sum-of-squares objective stops improving.
Also analyze: per-iteration time complexity, memory usage and how to reduce it, handling of empty clusters, the effect of feature scaling and outliers, methods for choosing k (elbow, silhouette, BIC), why the objective cannot increase across an iteration, and how a mini-batch version would differ and when you would use it.
What is expected: a written technical answer for Part A with correct equations, shapes, and parameter counts; working, vectorized code for Part B with a documented interface and sensible defaults; and a discussion of trade-offs and failure modes.
Hints
Hint 1
Think about what assumptions each architecture bakes into the data, and how receptive field grows as a function of depth, kernel size, stride, and dilation.
Hint 2
The cell-state recurrence is a near-identity additive path; expand the gradient of c_t with respect to c_{t-1} to see why.
Hint 3
Use the squared-distance expansion ||x-mu||^2 = ||x||^2 - 2x.mu + ||mu||^2 to turn assignment into one matrix multiplication; also watch for empty clusters and tiny negative values from floating point.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Part A: CNN, RNN, and LSTM
Architectural contrasts
| Property | CNN | RNN |
|---|---|---|
| Built-in assumption | Neighboring inputs are related; features are position-independent | Inputs arrive in order; a state summarizes the prefix seen so far |
| Weight sharing | The same kernel is reused at every spatial/temporal position | The same transition matrices are reused at every time step |
| Receptive field | Grows with depth: roughly 1 + L(k-1) for L stride-1 layers with kernel width k; stride, pooling, or dilation enlarge it faster | Potentially unbounded, since h_t depends on x_1..x_t |
| Long-range modeling | Requires sufficient depth, dilation, or global pooling | Gradient path length grows linearly with the dependency distance, so vanilla RNNs suffer vanishing/exploding gradients |
| Parallelism | All positions computed at once | Strictly sequential across time steps |
Images (224×224 RGB). A CNN is the natural choice. Adjacent pixels are strongly correlated, and an object should be recognized wherever it appears, which is exactly translation equivariance plus locality. A single 3×3×3→64 kernel has 1,728 weights; a dense layer over all 150,528 pixels would need millions of parameters and would discard spatial structure. Feeding an image to an RNN imposes an arbitrary scan order on 2D content and provides no useful equivariance.
Variable-length text. RNNs/LSTMs and Transformers consume tokens in order and handle arbitrary lengths naturally. A 1D CNN also accepts variable lengths (pad, then pool globally), but its context is bounded by its receptive field unless dilated convolutions are used — with dilation doubling per layer, the receptive field grows exponentially in depth (TCN/WaveNet-style).
When a 1D CNN suffices. Local-pattern tasks (keyword spotting, intent detection, bag-of-ngrams sentiment), latency-critical inference (convolution parallelizes across positions), and causal modeling where dilated convolutions reach back far enough. It is a poor fit when the task requires content-dependent long-range interactions such as coreference or machine translation — there attention wins.
LSTM equations
With σ the logistic sigmoid and ⊙ elementwise multiplication:
i_t = σ(W_i x_t + U_i h_{t-1} + b_i) input gate
f_t = σ(W_f x_t + U_f h_{t-1} + b_f) forget gate
o_t = σ(W_o x_t + U_o h_{t-1} + b_o) output gate
g_t = tanh(W_g x_t + U_g h_{t-1} + b_g) candidate
c_t = f_t ⊙ c_{t-1} + i_t ⊙ g_t
h_t = o_t ⊙ tanh(c_t)
Why the cell state helps. For a vanilla RNN, ∂h_t/∂h_{t-1} = diag(tanh')·U; chaining T steps multiplies Jacobians whose scale behaves like ‖U‖^T, so gradients shrink geometrically. For the LSTM, ∂c_t/∂c_{t-1} = diag(f_t) directly, plus indirect terms through h_{t-1}. Back-propagating along the cell path yields a product of forget gates rather than a product of weight matrices with squashing derivatives. If the network learns f ≈ 1 — commonly encouraged by initializing b_f = 1 — the error signal flows almost unchanged (the "constant error carousel"). This mitigates but does not eliminate vanishing gradients, and exploding gradients still require clipping.
Shapes and parameters
Input (32, 100, 64), hidden 128, batch_first=True, one layer:
| Model | output | h_n | c_n |
|---|---|---|---|
| Unidirectional | (32, 100, 128) | (1, 32, 128) | (1, 32, 128) |
| Bidirectional | (32, 100, 256) | (2, 32, 128) | (2, 32, 128) |
Bidirectional output concatenates the two directions (128+128); h_n/c_n keep 128 per direction. Unidirectional parameters: 4·(64·128 + 128·128 + 128) = 98,816, or 99,328 in PyTorch, which stores separate W and U bias vectors per gate. Bidirectional doubles this.
Part B: K-means
Algorithm and objective
K-means minimizes J = Σ_i ‖x_i − μ_{c(i)}‖² by coordinate descent: (1) assign each point to its nearest centroid; (2) replace each centroid with the mean of its assigned points.
k-means++ seeding. Choose the first centroid uniformly at random. For each subsequent centroid, sample a point with probability proportional to its squared distance to the closest centroid chosen so far. This is O(log k)-competitive with the optimum in expectation and avoids the poor local minima that uniform random seeding often produces.
Monotonicity. With centroids fixed, the assignment step picks the per-point minimizer of ‖x_i − μ‖², so J cannot increase. With assignments fixed, f(μ) = Σ_{x∈S}‖x − μ‖² is strictly convex with minimizer μ = mean(S), so the update step cannot increase J either. Therefore J is non-increasing over a full iteration. Since J ≥ 0 and there are finitely many partitions, the algorithm terminates, at a local optimum only.
Complexity and memory. Each iteration costs O(n·k·d) time. Using ‖x − μ‖² = ‖x‖² − 2x·μ + ‖μ‖², assignment becomes one n×d by d×k matmul. The distance matrix needs O(nk) memory; for large n·k, compute assignments in row chunks so memory is O(chunk·k).
Edge cases. If a cluster ends up empty, re-seed its centroid at the point currently worst fit (largest distance to its own centroid), using distinct points. During k-means++, if all remaining distances are zero (duplicate points), fall back to uniform sampling. Require k ≤ n.
Preprocessing. Standardize features, since Euclidean distance is dominated by large-magnitude dimensions; PCA can help when d is large. The mean is not robust, so clip or remove outliers, or use k-medoids/k-medians. K-means assumes roughly spherical, comparable-size clusters — use a GMM otherwise. Run multiple seeds and keep the lowest J.
Choosing k. Elbow on the J(k) curve (subjective), silhouette score s = (b − a)/max(a, b) averaged over points (O(n²), so subsample), or BIC for a spherical-GMM surrogate with a parameter penalty. A downstream supervised metric is best when available.
Mini-batch variant. Sample a batch of size B, assign those points, and update centroids with a learning-rate-weighted step, e.g. μ_j ← μ_j + η·(batch_mean_j − μ_j), with η decaying or set to 1/B. Use it for very large n, streaming data, or limited memory; expect noisier convergence than full batch.
Implementation
import numpy as np
def _sq_dists(X, C):
"""Pairwise squared Euclidean distances, shape (n, k)."""
d = (X * X).sum(1)[:, None] - 2.0 * X @ C.T + (C * C).sum(1)[None, :]
np.maximum(d, 0.0, out=d) # guard against round-off negatives
return d
def _kmeans_pp(X, k, rng):
n = X.shape[0]
centers = np.empty((k, X.shape[1]), dtype=float)
centers[0] = X[rng.integers(n)]
min_d2 = _sq_dists(X, centers[:1]).ravel()
for j in range(1, k):
total = min_d2.sum()
idx = rng.integers(n) if total <= 0 else rng.choice(n, p=min_d2 / total)
centers[j] = X[idx]
min_d2 = np.minimum(min_d2, _sq_dists(X, centers[j:j + 1]).ravel())
return centers
def kmeans(X, k, max_iter=300, tol=1e-6, n_init=10, seed=0):
"""Return (centers, labels, inertia). X: (n, d) float array."""
X = np.asarray(X, dtype=float)
n, d = X.shape
if not 1 <= k <= n:
raise ValueError("k must satisfy 1 <= k <= n")
rng = np.random.default_rng(seed)
best = None
for _ in range(n_init):
C = _kmeans_pp(X, k, rng)
prev = np.inf
for _ in range(max_iter):
dists = _sq_dists(X, C)
labels = dists.argmin(1)
inertia = dists[np.arange(n), labels].sum()
# Re-seed empty clusters at worst-fit points.
counts = np.bincount(labels, minlength=k)
empty = np.flatnonzero(counts == 0)
if empty.size:
worst = np.argsort(-dists[np.arange(n), labels])
picks = worst[:empty.size]
C[empty] = X[picks]
# Update centroids as cluster means.
for j in range(k):
if counts[j] > 0:
C[j] = X[labels == j].mean(0)
if prev - inertia <= tol * max(1.0, prev):
break
prev = inertia
if best is None or inertia < best[2]:
best = (C.copy(), labels.copy(), inertia)
return best
The final returned inertia is computed against the centroids used for that assignment; a production version should recompute labels and inertia once after the last centroid update so the two are consistent.