I need to make a code generation from Python to Matlab, and I'm new to Python.
Although there are some websites which give definitions of what numpy.bincount
and what numpy.argmax
are, they don't give a simple example which is understandable for new beginners.
There is such a statement in a Python algorithm:
numpy.argmax(numpy.bincount(dlabel))
dlabel
is a matrix. What does this function exactly do? This calculation is very important for me, and I don't want to make rush because of misunderstanding of this simple code statement.
Could you show me example for numpy.bincount
, and numpy.argmax
on matrices differently, and briefly?
numpy.argmax(numpy.bincount(dlabel))
returns the most common value found in dlabel
.
To break it down, np.bincount()
will return the count of each value in an array of non-negative integers and return an array with the count at the appropriate index (Python arrays are indexed from 0). For example:
>>> np.bincount(np.array([1,2,3,2,4,1,1,0]))
array([1, 3, 2, 1, 1], dtype=int32)
# So '0' appears once, '1' appears three times, ...
It also works for int arrays that don't start at zero
>>> np.bincount(np.array([3, 3, 3, 3, 3, 4]))
array([0, 0, 0, 5, 1], dtype=int32)
# So '3' appears 5 times, '4' appears three times, ...
np.argmax()
returns the index of the (first) maximum value in an array.
>>> np.argmax([1, 3, 2, 1, 1])
1
# maximum value is '3', with index '1'
So combining the two functions, we can find that 1
appears most often in [1,2,3,2,4,1,1,0]
(it appears 3 times).
>>> np.argmax(np.bincount([1,2,3,2,4,1,1,0]))
1