+1 vote
in Machine Learning by (10.2k points)
I am running an ML model on some data and I need to find the frequency of each class in the list of classes. Is there any function that I can use instead of using for loop?

1 Answer

+2 votes
by (60.2k points)
selected by
 
Best answer

There are a few functions that you can use to find the frequency of each class in the labels.

1. Using bincount() function

You can use the bincount() function of the Numpy module. It returns a list of occurrences of each value in an array.

>>> import numpy as np

>>> y=np.asarray([1,0,0,1,1,0,0,0,0,0,1])

>>> np.bincount(y)

array([7, 4])

In the above example, the frequency of 0 is 7, and that of 1 is 4. 

2. Using Counter() function

You can also use the Counter() function of the collections module. It returns a dictionary with class as keys and its frequency as values.

>>> from collections import Counter

>>> Counter(y)

Counter({0: 7, 1: 4})


...