Python - taking most frequent element from array/converting numpy array to std array
Question: I'm in the process of implementing a K-nearest neighbour algorithm in Python
(for those of you that don't know about learning, it's an algorithm used to
classify objects based on data that is already classified, using Euclidean
distance).

I've got my distances computed, and I can take the k nearest distances, and
find the classes of those objects. My problem is, if K is greater than 1, say
3 or 5, I'm not sure how I can get the most frequent element in the list.

For example, my output is:

    
    
    [10, 9, 7, 10]
    

10 occurs the most, so I'd like to return this number. In case of a tie (2 or
more elements occuring the same frequency), it returns an error (I can deal
with this myself). I'd just like some opinion on how to return the maximum of
the above list. (**Using python 2.6.6** so I can't use the collections
imports).

Second question:

I'm attempting to convert a numpy array to a normal array. My code looks like
this:

    
    
    def getClassesOfIndexes(l):
        tmp1 = []
        for i in l:
            tmp1.append(classes[i])
        return tmp1
    
    print(getClassesOfIndexes([1024, 9128, 394, 39]))
    

This prints something like: `[array([10], dtype=uint8), array([7],
dtype=uint8), array([10], dtype=uint8), array([9], dtype=uint8)]`

What could I do for it to simply return `[10, 7, 10, 9]`?

Thanks for any help.


Answer: **Question 2** is the easier (though in the future, please post unrelated
questions as two separate questions on SO). The `tolist` function
automatically converts numpy arrays to regular lists
<http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tolist.html>

**Question 1** is also pretty straightforward. You say you want "the most
frequent element in the list". Here's a complete discussion [Python most
common element in a list](http://stackoverflow.com/questions/1518522/python-
most-common-element-in-a-list). One solution is to map each element to a
dictionary of its frequency, and then grab the key corresponding to the
largest value in the map. This might look like

    
    
    ...
    freq_map = {my_list.count(val):val for val in set(my_list)}
    return freq_map[max(freq_map.keys())]
    

