← 返回 amazon 的题目列表K-Nearest Neighbors Implementation
类型:online_judge
Implement a K-Nearest Neighbors (KNN) algorithm. Your task is to perform classification using a given dataset and return the predicted class for each test sample. Assume the dataset contains only numerical data. You can assume the value of k is 3.
Input:
A training dataset, where each line represents a set of features followed by a label, separated by a space. Features are separated by commas.
A testing dataset, formatted the same way, where the output only needs to include the predicted class labels for the test data.
Output:
The predicted class label for each test sample.
You need to implement the following:
Compute Euclidean distance.
Predict based on the labels of the nearest k samples.
Example: Assume the input training dataset is:
1,2,3 A
2,3,4 B
3,4,5 A
And the test data is:
2,2,2
3,3,3
The output should be:
A
B
Example
Input
1,2,3 A
2,3,4 B
3,4,5 A
2,2,2
3,3,3