Home > Software engineering >  How to get maximum accuracy from a multi-dimensional array?
How to get maximum accuracy from a multi-dimensional array?

Time:02-19

I have a multi-dimensional array like in the picture. If I search for the maximum accuracy using max(accuracy), it will calculate the max accuracy based on the k value.

enter image description here

K = np.arange(1, 5)
metric = ['euclidean', 'manhattan']

accuracy = []

for k in K:
    for m in metric:
        m2 = KNeighborsClassifier(n_neighbors=k, metric=m).fit(X_train_scaled, y_train_scaled)
        acc = m2.score(X_test_scaled, y_test_scaled)
        accuracy.append([k, m, acc])

print(f'Accuracy = {accuracy}')
print(f'\nMax Accuracy: \n{max(accuracy)}')

How do I get the max accuracy based on the accuracy value?

CodePudding user response:

accuracy is a list constructed in a loop. Since accuracy score is the third element in each sublist, you can find the maximum using max function by passing a lambda function that selects the last element of a list to the key parameter. From the docs:

key specifies a function of one argument that is used to extract a comparison key from each list element (for example, key=str.lower). The key corresponding to each item in the list is calculated once and then used for the entire sorting process.

For example:

>>> accuracy = [[1,'a',1], [1,'b',10], [2,'c',5], [3,'d',3]]
>>> highest_accuracy = max(accuracy, key=lambda x: x[-1])
>>> print(highest_accuracy)
[1, 'b', 10]
  • Related