首页 > 解决方案 > Keras:获取张量元素的数值

问题描述

我正在尝试制作一个自定义损失函数,它根据预测值和实际值的范围返回不同的值。但是我无法比较这些值,因为变量是张量,而且我找不到获取它们唯一元素数值的方法(我的输出是一维的)。我认为这将是一项简单的任务,但我已经尝试了很多事情(转换为 numpy 数组、转换为列表、获取规范、获取最小值、使用 eval)并且没有任何效果。

这是我的代码*:

def myloss(y, h):
    if 0.5 < y < 0.7 and 0.5 < h < 0.7:  # LINE 2
        return 0
    return abs(y - h)
   
def custom_loss(target, pred):
    return kb.mean(kb.map_fn(lambda e: myloss(e[0], e[1]), [target, pred]))

第 2 行是我需要这些值的地方(y 和 h 是类似 的张量Tensor("custom_loss/map/while/TensorArrayV2Read/TensorListGetItem:0", shape=(1,), dtype=int64))。

如果我运行它,我会收到错误

TypeError:预期 int64 传递给 op 'Greater' 的参数 'y',取而代之的是 0.5 类型的 'float'。错误:预期为 int64,取而代之的是 0.5 类型的“float”。

这是Colab *上的一个最小示例: https ://colab.research.google.com/drive/1CA7GCU-dfh-zrdTPAt-tLNTJpz8n2rN4#scrollTo=OPGlDAEAaosM 。随意编辑和测试。

[*] 为了便于阅读,我已经简化了函数。

标签: pythontensorflowkerasdeep-learningtensor

解决方案


投射到浮动:

def myloss(y, h):
    y = tf.cast(y, tf.float32)
    if tf.constant(0.5) < y < tf.constant(0.7) and tf.constant(0.5) < h < tf.constant(0.7):  # LINE 2
        return 0. # <= add dot here
    return abs(y - h)

推荐阅读