6

I'm trying

print(Y)
print(Y.shape)

class_weights = compute_class_weight('balanced',
                                     np.unique(Y),
                                     Y)
print(class_weights)

But this gives me an error:

ValueError: classes should include all valid labels that can be in y

My Y looks like:

       0  1  2  3  4
0      0  0  1  0  0
1      1  0  0  0  0
2      0  0  0  1  0
3      0  0  1  0  0
...
14992     0  0  1  0  0
14993      0  0  1  0  0

And my Y.shape looks like: (14993, 5)

In my keras model, I want to use the class_weights as it is an uneven distribution:

model.fit(X, Y, epochs=100, shuffle=True, batch_size=1500, class_weights=class_weights, validation_split=0.05, verbose=1, callbacks=[csvLogger])
Shamoon
  • 41,293
  • 91
  • 306
  • 570

2 Answers2

6

Just transform the one-hot encoding to categorical labels:

from sklearn.utils import class_weight

y = Y.idxmax(axis=1)

class_weights = class_weight.compute_class_weight('balanced',
                                                  np.unique(y),
                                                  y)

# Convert class_weights to a dictionary to pass it to class_weight in model.fit
class_weights = dict(enumerate(class_weights))
Andreas K.
  • 9,282
  • 3
  • 40
  • 45
3

Create some sample data with at least one example per class

df = pd.DataFrame({
    '0': [0, 1, 0, 0, 0, 0],
    '1': [0, 0, 0, 0, 1, 0], 
    '2': [1, 0, 0, 1, 0, 0],
    '3': [0, 0, 1, 0, 0, 0],
    '4': [0, 0, 0, 0, 0, 1],
})

Stack the columns (convert from wide to long table)

df = df.stack().reset_index()
>>> df.head()

  level_0   level_1     0
0   0       0       0
1   0       1       0
2   0       2       1
3   0       3       0
4   0       4       0

Get the class for each data point

Y = df[df[0] == 1]['level_1']
>>> Y
2     2
5     0
13    3
17    2
21    1
29    4

Compute class weights

class_weights = compute_class_weight(
    'balanced', np.unique(Y), Y
)
>>> print(class_weights)
[1.2 1.2 0.6 1.2 1.2]
ulmefors
  • 516
  • 3
  • 11