← 返回 openai 的题目列表Implement 1-Nearest-Neighbor (1NN) and a Simple Neural Network in NumPy, then Modify to Use L1 Distance (Follow-up)
类型:online_judge
Problem: Implement 1NN and a Simple Neural Network in NumPy, then Modify to Use L1 Distance (Follow-up)
Given training features X_train with labels y_train, and test features X_test:
Implement a 1-Nearest-Neighbor (1NN) predictor in NumPy:
For each test sample in X_test, find the single closest sample in X_train.
Predict the label of that nearest training sample.
The initial version uses L2 (Euclidean) distance.
Implement a simple feed-forward neural network in NumPy:
Build a small MLP from scratch using NumPy (e.g., linear layers + non-linear activations) for forward inference.
(If required) implement training, or at least the forward pass that produces outputs.
Follow-up: change the 1NN distance metric to L1 (Manhattan) distance:
Replace the distance function with L1: [ d(x, z) = \sum_i |x_i - z_i| ]
Explain/implement how to compute pairwise L1 distances between X_test and X_train efficiently in NumPy and produce predictions.
I/O Convention (typical interview form)
Input: X_train has shape (N, D), y_train has shape (N,), X_test has shape (M, D).
Output: return y_pred with shape (M,).
Constraints (typical interview focus)
Must be implemented in NumPy; prefer vectorization (minimize Python loops).
Be careful with broadcasting and shapes.
Test Cases
Below are 5 test cases to validate 1NN (for the L2 version; the L1 version only changes the metric):
Case 1
Input:
X_train = [[0,0],[1,1],[2,2]]
y_train = [0,1,1]
X_test = [[1.1,1.1],[0.2,0.1]]
Expected output: [1,0]
Case 2
Input:
X_train = [[-1,0],[0,0],[3,0]]
y_train = [5,6,7]
X_test = [[2,0],[-0.6,0]]
Expected output: [7,5]
Case 3
Input:
X_train = [[1,2,3],[4,5,6],[7,8,9]]
y_train = [10,11,12]
X_test = [[6,7,8]]
Expected output: [12]
Case 4 (duplicate points)
Input:
X_train = [[0,0],[0,0],[1,0]]
y_train = [1,2,3]
X_test = [[0,0]]
Expected output: [1]
Case 5
Input:
X_train = [[0,1],[1,0],[1,1]]
y_train = [0,1,2]
X_test = [[0,0],[2,2]]
Expected output: [0,2]
Example
Input
X_train=[[0,0],[1,1],[2,2]]
y_train=[0,1,1]
X_test=[[1.1,1.1],[0.2,0.1]]
Output
[1, 0]