简体   繁体   中英

TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. when writing a custom metric function in keras

Keras version: 2.2.4

Tensorflow version: 1.14.0

TypeError: Using a tf.Tensor as a Python bool is not allowed. Use if t is not None: instead of if t: to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.

I am trying to write a custom metric function in Keras and couldn't get through because of the above error. Please find the below code blocks I am using.

def IOU(y_true, y_pred):
    intersections = 0
    unions = 0
    gt = y_true
    pred = y_pred

    # Compute interection of predicted (pred) and ground truth (gt) bounding boxes
    diff_width = np.minimum(gt[:,0] + gt[:,2], pred[:,0] + pred[:,2]) - np.maximum(gt[:,0], pred[:,0])
    diff_height = np.minimum(gt[:,1] + gt[:,3], pred[:,1] + pred[:,3]) - np.maximum(gt[:,1], pred[:,1])
    intersection = diff_width * diff_height

    # Compute union
    area_gt = gt[:,2] * gt[:,3]
    area_pred = pred[:,2] * pred[:,3]
    union = area_gt + area_pred - intersection

    # Compute intersection and union over multiple boxes
    for j, _ in enumerate(union):
      if union[j] > 0 and intersection[j] > 0 and union[j] >= intersection[j]:
        intersections += intersection[j]
        unions += union[j]

    # Compute IOU. Use epsilon to prevent division by zero
    iou = np.round(intersections / (unions + epsilon()), 4)
    return iou

model = create_model() 

model.compile(loss="mean_squared_error", optimizer="adam", metrics=[IOU])

model.fit(X_train,y_train, 
          validation_data=(X_val, y_val),
          epochs=EPOCHS,
          batch_size=32,
          verbose=1)

Please help me in writing a custom metric function in keras, by accessing y_true and y_pred . Thanks in advance.

Using tf.py_func solved the issue for me. Given below are the code blocks with the necesarry changes to the above mentioned code blocks in the question.

def IOU(y_true, y_pred):
        intersections = 0
        unions = 0

        gt = y_true
        pred = y_pred
        # Compute interection of predicted (pred) and ground truth (gt) bounding boxes
        diff_width = np.minimum(gt[:,0] + gt[:,2], pred[:,0] + pred[:,2]) - np.maximum(gt[:,0], pred[:,0])
        diff_height = np.minimum(gt[:,1] + gt[:,3], pred[:,1] + pred[:,3]) - np.maximum(gt[:,1], pred[:,1])
        intersection = diff_width * diff_height

        # Compute union
        area_gt = gt[:,2] * gt[:,3]
        area_pred = pred[:,2] * pred[:,3]
        union = area_gt + area_pred - intersection

        # Compute intersection and union over multiple boxes
        for j, _ in enumerate(union):
          if union[j] > 0 and intersection[j] > 0 and union[j] >= intersection[j]:
            intersections += intersection[j]
            unions += union[j]

        # Compute IOU. Use epsilon to prevent division by zero
        iou = np.round(intersections / (unions + epsilon()), 4)
        # This must match the type used in py_func
        iou = iou.astype(np.float32)
        return iou

def IoU(y_true, y_pred):
    iou = tf.py_func(IOU, [y_true, y_pred], tf.float32)
    return iou

model = create_model()
model.compile(loss="mean_squared_error", optimizer="adam", metrics=[IoU])
model.fit(X_train,y_train, validation_data=(X_val, y_val), epochs=EPOCHS, batch_size=32,
          verbose=1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM