我正在使用中性网络进行多类别分类。有3种不平衡类,因此我想使用散焦来处理不平衡。因此,我使用自定义损失函数来拟合Keras顺序模型。我在网上找到了多个版本的失焦函数代码,但它们返回了相同的错误消息,基本上是说输入大小是预期的浴槽大小1.有人可以看一下这个问题,让我知道是否可以修理它?我真的很感激!!!
model = build_keras_model(x_train,name='training1')
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].