Isomap From Scratch

Quick Overview

Implement Isomap with NumPy and SciPy: build a symmetric k-nearest-neighbour graph, compute geodesic shortest-path distances on it, and embed them with classical MDS. It tests graph construction, double centring, eigendecomposition with a sign convention, and the ways manifold learning breaks on real data.

Isomap From Scratch

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: hard

Interview Round: Other

Implement Isomap for data `X` (shape `(n, d)`) as four functions: build a symmetric k-nearest-neighbour graph, compute all-pairs geodesic (shortest-path) distances on it, and embed those distances with classical MDS. `isomap` returns an `(n, n_components)` array. - `knn_graph(X, n_neighbors)` returns a dense `(n, n)` matrix with Euclidean edge weights (0 means no edge), symmetrised as the union of each point's k nearest neighbours (self excluded), with a zero diagonal. Raise `ValueError` unless `1 ≤ n_neighbors < n`. - `geodesic_distances(X, n_neighbors)` returns the undirected shortest-path distances on that graph. Raise `ValueError` if the graph is disconnected. - `classical_mds(D, n_components=2)` double-centres `-0.5 * D**2`, takes the top eigenpairs by descending eigenvalue, clips negative eigenvalues to 0, and scales the eigenvectors by `sqrt(eigenvalue)`. Flip each output column so its largest-magnitude entry is positive. - `isomap(X, n_neighbors, n_components=2)` is `classical_mds` applied to `geodesic_distances`. `numpy` and `scipy` are available. On inputs without tied neighbour distances, results must match `sklearn.manifold.Isomap` (dense eigensolver, Dijkstra) up to numerical tolerance. Example: ```python X = np.array([[0.], [1.], [3.], [6.], [10.]]) knn_graph(X, 1) # edges 0-1:1, 1-2:2, 2-3:3, 3-4:4 geodesic_distances(X, 1) # |x_i - x_j| isomap(X, 1, n_components=1) # [[-4.], [-3.], [-1.], [2.], [6.]] ``` With one neighbour each, the points form a chain, so every geodesic equals `|x_i - x_j|` and the embedding is the centred coordinates (the mean is 4). ```hint Graph representation SciPy's shortest-path routines accept a matrix where 0 means no edge and can treat a directed graph as undirected. Check that your symmetrisation and the solver's notion of an undirected edge agree. ``` ```hint Double centring With `J = I - 11ᵀ/n`, the matrix `-0.5 J D² J` is a Gram matrix when `D` is Euclidean. `D**2` is elementwise, and `np.linalg.eigh` returns eigenvalues in ascending order. ``` ```hint Determinism Two things can make the output depend on implementation details: ties among neighbour distances and eigenvector signs. Decide how each one is resolved. ``` ### Constraints & Assumptions - `X` is a real array of shape `(n, d)`, and `1 ≤ n_neighbors < n`. - Dense `(n, n)` matrices are expected, so assume `n` is small enough for `O(n²)` memory and an `O(n³)` eigendecomposition. - The `D` passed to `classical_mds` is a symmetric `(n, n)` distance matrix with a zero diagonal. - Only `numpy` and `scipy` are used in the implementation. ### What a Strong Answer Covers - A kNN graph that excludes self, applies the union rule, and has a defined tie order. - Shortest paths on the undirected graph, with a check for disconnection. - Double centring, eigenpair selection in descending order, clipping, scaling and the sign rule. - The time and memory cost of each stage, and which stage dominates. - Failure modes: disconnected graphs, short-circuit edges from a large `n_neighbors`, duplicate points, and negative eigenvalues. ### Follow-up Questions - How would you embed a new, unseen point without recomputing everything? - What breaks at n = 100,000 and how would you scale it? - Why can the double-centred matrix have negative eigenvalues, and what does it mean?

Overview: Implement Isomap with NumPy and SciPy: build a symmetric k-nearest-neighbour graph, compute geodesic shortest-path distances on it, and embed them with classical MDS. It tests graph construction, double centring, eigendecomposition with a sign convention, and the ways manifold learning breaks on real data.

PracHub logo
General
Nov 24, 2026
hardMachine Learning EngineerOtherMachine Learning
0
0

Implement Isomap for data X (shape (n, d)) as four functions: build a symmetric k-nearest-neighbour graph, compute all-pairs geodesic (shortest-path) distances on it, and embed those distances with classical MDS. isomap returns an (n, n_components) array.

  • knn_graph(X, n_neighbors) returns a dense (n, n) matrix with Euclidean edge weights (0 means no edge), symmetrised as the union of each point's k nearest neighbours (self excluded), with a zero diagonal. Raise ValueError unless 1 ≤ n_neighbors < n .
  • geodesic_distances(X, n_neighbors) returns the undirected shortest-path distances on that graph. Raise ValueError if the graph is disconnected.
  • classical_mds(D, n_components=2) double-centres -0.5 * D**2 , takes the top eigenpairs by descending eigenvalue, clips negative eigenvalues to 0, and scales the eigenvectors by sqrt(eigenvalue) . Flip each output column so its largest-magnitude entry is positive.
  • isomap(X, n_neighbors, n_components=2) is classical_mds applied to geodesic_distances .

numpy and scipy are available. On inputs without tied neighbour distances, results must match sklearn.manifold.Isomap (dense eigensolver, Dijkstra) up to numerical tolerance.

Example:

X = np.array([[0.], [1.], [3.], [6.], [10.]])
knn_graph(X, 1)            # edges 0-1:1, 1-2:2, 2-3:3, 3-4:4
geodesic_distances(X, 1)   # |x_i - x_j|
isomap(X, 1, n_components=1)
# [[-4.], [-3.], [-1.], [2.], [6.]]

With one neighbour each, the points form a chain, so every geodesic equals |x_i - x_j| and the embedding is the centred coordinates (the mean is 4).

Constraints & Assumptions

  • X is a real array of shape (n, d) , and 1 ≤ n_neighbors < n .
  • Dense (n, n) matrices are expected, so assume n is small enough for O(n²) memory and an O(n³) eigendecomposition.
  • The D passed to classical_mds is a symmetric (n, n) distance matrix with a zero diagonal.
  • Only numpy and scipy are used in the implementation.

What a Strong Answer Covers Guidance

  • A kNN graph that excludes self, applies the union rule, and has a defined tie order.
  • Shortest paths on the undirected graph, with a check for disconnection.
  • Double centring, eigenpair selection in descending order, clipping, scaling and the sign rule.
  • The time and memory cost of each stage, and which stage dominates.
  • Failure modes: disconnected graphs, short-circuit edges from a large n_neighbors , duplicate points, and negative eigenvalues.

Follow-up Questions Guidance

  • How would you embed a new, unseen point without recomputing everything?
  • What breaks at n = 100,000 and how would you scale it?
  • Why can the double-centred matrix have negative eigenvalues, and what does it mean?