我正在使用中性网络进行多类分类。有 3 个不平衡的类,所以我想使用焦点损失来处理不平衡。所以我使用自定义损失函数来适应 Keras 顺序模型。我尝试了在网上找到的焦点损失函数的多个版本的代码,但它们返回相同的错误消息,基本上说输入大小是浴缸大小,而预期为 1。任何人都可以看看这个问题,让我知道你是否可以修理它?对此,我真的非常感激!!!
model = build_keras_model(x_train, name='training1')
</p>
class FocalLoss(keras.losses.Loss):
def __init__(self, gamma=2., alpha=4.,
reduction = tf.keras.losses.Reduction.AUTO, name='focal_loss'):
super(FocalLoss, self).__init__(reduction=reduction,
name=name)
self.gamma = float(gamma)
self.alpha = float(alpha)
def call(self, y_true, y_pred):
epsilon = 1.e-9
y_true = tf.convert_to_tensor(y_true, tf.float32)
y_pred = tf.convert_to_tensor(y_pred, tf.float32)
model_out = tf.add(y_pred, epsilon)
ce = tf.multiply(y_true, -tf.math.log(model_out))
weight = tf.multiply(y_true, tf.pow(
tf.subtract(1., model_out), self.gamma))
fl = tf.multiply(self.alpha, tf.multiply(weight, ce))
reduced_fl = tf.reduce_max(fl, axis=1)
return tf.reduce_mean(reduced_fl)
model.compile(optimizer = tf.keras.optimizers.Adam(0.001),
loss = FocalLoss(alpha=1),
metrics=['accuracy'])
class_weight = {0: 1.,
1: 6.,
2: 6.}
# fit the model (train for 5 epochs)
history = model.fit(x=x_train, y=y_train, batch_size=64, epochs=5,
class_weight = class_weight)
ValueError: Can not squeeze dim[0], expected a dimension of 1, got 64 for 'loss/output_1_loss/weighted_loss/Squeeze' (op: 'Squeeze') with input shapes: [64].