← 返回 openai 的题目列表Implement 1-Nearest Neighbor (1NN) Classifier with NumPy; Rewrite as Neural Network Weights
类型:online_judge
Implement 1NN with NumPy; Rewrite into a “Neural Network Weights” Form
You are given training features X_train with labels y_train, and test features X_test.
Part 1: Implement 1NN Prediction
Implement a 1-Nearest Neighbor (1NN) classifier using NumPy only (no sklearn-style models):
For each sample in X_test, compute distances to all samples in X_train
Find the training sample with the minimum distance
Predict its label
Distance metric: Euclidean (L2).
Input
X_train: float array of shape (n_train, d)
y_train: int array of shape (n_train,)
X_test: float array of shape (n_test, d)
Output
y_pred: int array of shape (n_test,)
Constraints
n_train, n_test may be large; prefer vectorization (looping over n_test is acceptable, but avoid heavy nested loops).
Part 2: Rewrite 1NN as “Neural Network Weights”
Without changing the behavior of 1NN, rewrite the computation in terms of “weights/parameters” akin to neural network layers (e.g., matrix multiplications and additions), and clearly state/return those parameters.
Note: The original post does not specify the exact required format (what weights to output, fixed depth, allowed non-linearities/argmin, etc.), so this part is necessarily high-level.
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]