Mun Says
Mun Says

Reputation: 97

ValueError: `class_weight` must contain all classes in the data. The classes {1, 2, 3} exist in the data but not in `class_weight`

ValueError: class_weight must contain all classes in the data. The classes {1, 2, 3} exist in the data but not in class_weight

I am trying to assign class-weights to my un-balanced classes but after model.fit() it generates this error although i seen other solutions already given for this problem but still unable to solve it.

test_split=round(n*2/3)
x_train=x[:test_split]
y_train=y[:test_split]
x_test=x[test_split:]
y_test=y[test_split:]

class_weight_list = compute_class_weight('balanced', numpy.unique(y_train), y_train)
class_weight = dict(zip(numpy.unique(y_train), class_weight_list))
x_train=x_train.astype('float64')
x_test=x_test.astype('float64')

x_train/=255
x_test/=255

y_train=keras.utils.to_categorical(y_train, num_classes)
y_test=keras.utils.to_categorical(y_test, num_classes)
hist=model.fit(x_train, y_train, 
               batch_size=batch_size,
               epochs=epochs,
               validation_data=(x_test, y_test),
               callbacks=[checkpoint],
               class_weight=class_weight
               )

Upvotes: 3

Views: 3569

Answers (1)

Ioannis Nasios
Ioannis Nasios

Reputation: 8527

try label encoding first

EDIT

encoder = LabelEncoder()
encoder.fit(y_train)
y_train= encoder.transform(y_train)
y_test= encoder.transform(y_test)

class_weight_list = compute_class_weight('balanced', numpy.unique(y_train), y_train)
class_weight = dict(zip(numpy.unique(y_train), class_weight_list))

y_train=keras.utils.to_categorical(y_train, num_classes)  

Upvotes: 1

Related Questions