Ошибка типа: использование `tf.Tensor` в качестве Python` bool` не допускается.при написании пользовательской метрической функции в керасе - PullRequest
1 голос
/ 03 июля 2019

Версия Keras: 2.2.4

Версия Tensorflow: 1.14.0

Ошибка типа: использование tf.Tensor в качестве Python bool не допускается.Используйте if t is not None: вместо if t:, чтобы проверить, определен ли тензор, и используйте операции TensorFlow, такие как tf.cond, для выполнения подграфов, обусловленных значением тензора.

Я пытаюсь написать пользовательскийметрическая функция в Керасе и не может пройти из-за вышеуказанной ошибки.Найдите приведенные ниже кодовые блоки, которые я использую.

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 и y_pred.Заранее спасибо.

1 Ответ

0 голосов
/ 03 июля 2019

Использование 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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...