Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I assign a class_weight in Keras in a simple way?

Can anyone tell me what is the simplest way to apply class_weight in Keras when the dataset is unbalanced please?

I only have two classes in my target.

Thanks.

like image 975
Javi Avatar asked Sep 05 '25 12:09

Javi


1 Answers

The class_weight parameter of the fit() function is a dictionary mapping classes to a weight value.

Lets say you have 500 samples of class 0 and 1500 samples of class 1 than you feed in class_weight = {0:3 , 1:1}. That gives class 0 three times the weight of class 1.

train_generator.classes gives you the proper class names for your weighting.

If you want to calculate this programmatically you can use scikit-learn´s sklearn.utils.compute_class_weight().

The function looks at the distribution of labels and produces weights to equally penalize under or over-represented classes in the training set.

See also this useful thread here: https://github.com/fchollet/keras/issues/1875

And this thread might also be of help: Is it possible to automatically infer the class_weight from flow_from_directory in Keras?

like image 98
petezurich Avatar answered Sep 08 '25 16:09

petezurich