All problems
KNN Regression
Problem
Predict a value for x_test as the mean of the target values of its k nearest neighbors in X_train, using Euclidean distance.
If k exceeds the number of training points, use all of them. Empty training data returns 0.0.
Hint
Sort by squared distance, take the first k targets, and average them.
Test cases
case 1
in: [[[0,0],[0,1],[10,10],[10,11]],[0,1,10,11],[1,0],2]
expected: 0.5
case 2
in: [[[1],[2],[3],[10]],[2,4,6,20],[4],3]
expected: 4
case 3
in: [[[0,0],[1,1],[2,2]],[0,2,4],[0,0],5]
expected: 2
case 4
in: [[[5,5],[6,5]],[10,16],[4,4],1]
expected: 10
Starter codePython
def knn_regression(X_train, y_train, x_test, k):
# Your code here
pass4 test cases · run your code against them in the editor