首页 > 解决方案 > TypeError:不允许使用 `tf.Tensor` 作为 Python `bool`。在 keras 中编写自定义度量函数时

问题描述

凯拉斯版本:2.2.4

张量流版本:1.14.0

TypeError:不允许将 atf.Tensor用作 Python 。bool使用if t is not None:而不是if t:测试是否定义了张量,并使用 TensorFlow 操作(例如 tf.cond)执行以张量值为条件的子图。

我正在尝试在 Keras 中编写一个自定义指标函数,但由于上述错误而无法通过。请找到我正在使用的以下代码块。

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)

y_true请通过访问和帮助我在 keras 中编写自定义指标函数y_pred。提前致谢。

标签: pythontensorflowkeras

解决方案


使用tf.py_func为我解决了这个问题。下面给出的是对问题中上述代码块进行必要更改的代码块。

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)

推荐阅读