qubvel / segmentation_models

Segmentation models with pretrained backbones. Keras and TensorFlow Keras.
MIT License
4.67k stars 1.03k forks source link

'Tensor' object has no attribute 'flatten' when do model.fit(). #530

Closed naiborhujosua closed 2 years ago

naiborhujosua commented 2 years ago

i use this metrics for my image segmentation models but i got AttributeError: 'Tensor' object has no attribute 'flatten' when do model.fit(). i cast the y_true to float32, still no luck. Anyone can help?

def dice_coef(y_true, y_pred, smooth=1):
    y_true_flattened = K.flatten(y_true)
    y_pred_flatten = K.flatten(y_pred)
    intersection = K.sum(y_true_flattened * y_pred_flatten)
    union = K.sum(y_true_flattened) + K.sum(y_pred_flatten)
    return (2.0 * intersection + smooth) / union + smooth

def dice_loss(y_true, y_pred):
    smooth = 1
    y_true_flattened = y_true.flatten()
    y_pred_flattened = y_pred.flatten()
    intersection = y_true_flattened * y_pred_flattened
    score = (2.0 * K.sum(intersection) + smooth) / (
        K.sum(y_true_flattened) + K.sum(y_pred_flattened) + smooth
    )
    return 1.0 - score

def iou_coef(y_true, y_pred, smooth):
    intersection = K.sum(K.abs(y_true, *y_pred), axis=[1, 2, 3])
    union = K.sum(y_true, [1, 2, 3] + K.sum(y_pred, [1, 2, 3])) - intersection
    iou = K.mean((intersection) + smooth / (union + smooth), axis=0)
    return iou

def bce_dice_loss(y_true, y_pred):
    return binary_crossentropy(tf.cast(y_true, tf.float32), y_pred) + 0.5 * dice_loss(
        tf.cast(y_true, tf.float32), y_pred
    )
saatvikmah commented 1 year ago

Can you send your correction of this issue, I'm facing the same problem :)