python - ValueError : `class_weight` must contain all classes in the data. 类{1,2,3}存在于数据中但不存在于 `class_weight`

标签 python numpy tensorflow deep-learning keras

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

我正在尝试为我的不平衡类分配类权重,但在 model.fit() 之后它会生成此错误,尽管我看到已经针对此问题提供了其他解决方案但仍然无法解决它。

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
               )

最佳答案

先尝试标签编码

编辑

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)  

关于python - ValueError : `class_weight` must contain all classes in the data. 类{1,2,3}存在于数据中但不存在于 `class_weight`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49031309/

相关文章:

python - ValueError:无效的终结点:https://s3..amazonaws.com

python 将一列的值与条件相加

python - 导入 matplotlib.pyplot 时出现随机 nan 错误

python - 内存减少 Tensorflow TPU v2/v3 bfloat16

python - 用于多项式展开的 2d numpy.power

python - 如何提取特定字符之间的单词

python - 是否有现有的库或脚本集可以用 Python 为 Google Calendar API 编写重复事件字符串?

python - 将 ctypes 指针转换为 float 的 numpy 数组

python - Tensorflow:对 tf.estimator.inputs.numpy_input_fn 函数进行故障排除

python - 使用 tensorflow 后端测试 keras 中多个类的加权分类交叉熵