Here’s a solution that’s a bit shorter and faster. If your one-hot encoded y is a np.array:
import numpy as np
from sklearn.utils.class_weight import compute_class_weight
y_integers = np.argmax(y, axis=1)
class_weights = compute_class_weight('balanced', np.unique(y_integers), y_integers)
d_class_weights = dict(enumerate(class_weights))
d_class_weights
can then be passed to class_weight
in .fit
.