# Selecting class weights for loss function

I have a machine learning task where I would like to weight losses based on the frequency of the categorical values appearing in the data. The binary solution can be seen below, but I'd like to know what to do about the case of n>2 categories.

w_0 = (n_0 + n_1) / (2.0 * n_0)
w_1 = (n_0 + n_1) / (2.0 * n_1)


The frequencies for the samples n0-n5 are:

n_0:     1552829
n_1:     14479
n_2:     13445
n_3:     13781
n_4:     18795
n_5:     64187

• What do you hope to get out of weighting the loss function?
– Dave
Aug 17 '21 at 18:54

Is that what you want?

w_0 = (n_0+n_1+ ... +n_5) / (5.0 * n+0)


If so, it can be achieved by:

    n = [n_0, n_1, n_2, ...]
w = []
for i in range(len(n)):
w[i] = sum(n) / (len(n)*(n[i]))


Notice that Sum(n)/Len(n) = Average(n), so you'd basically saying your loss-function is avg(n)/ni.