0

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)
  • What is the format of your data? NumPy ndarray/pandas dataframe/python list? – Sanjar Adilov Feb 12 '22 at 07:37
  • the format is pandas dataframe – Anabella Dominguez Feb 12 '22 at 18:06
  • If your main concert is how to implement your task, there is nothing special about `lambda`. Do something like this `[returnScore(i, xtrain, xtest, ytrain, ytest) for i in range(1, 26)]`. Also, if your dataset is a dataframe, then use tools like `sklearn.model_selection.train_test_split` to obtain train-test sets. – Sanjar Adilov Feb 13 '22 at 06:37

1 Answers1

0

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?

jpmuc
  • 1,092
  • 14
  • 30