'Trouble with python iteration of knn scores

Im new to python and sklearn and im still trying to figure out What exactly does lambda do and how would I go about getting the scores from my test data set, if anyone has any helpful tips that would be great, thank you!

Question: Now we will write a function that will initialize, fit and return score on test data for given values of k and Plot result Use values from 1 to 25(inclusive) and get score and plot as a bar graph Hint : you can use map or you can use simple loops

import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix

def returnScore(k, xtrain, xtest, ytrain, ytest):
  knn = KNeighborsClassifier(n_neighbors=k)
  knn.fit(xtrain, ytrain)
  return knn.score(xtest, ytest)


result = [*map(lambda i:returnScore(i,?,?,?,?), range(1,25))]
print(result)
plt.plot(result)


Solution 1:[1]

The scores are what knn.score() gives you. Basically is what you get in the result array. lambda functions in Python are anonymous functions. So you could equivalently write

def getscores(k):
    ...
    return returnScore(k,?,?,?,?)

result = [*map(getscores, range(1,25))]

but, in this case, it is easier to read when you use lambda functions. See How are lambdas useful?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jpmuc