【问题标题】:Keras: get numeric value of tensor elementKeras:获取张量元素的数值
【发布时间】:2021-04-04 04:29:00
【问题描述】:

我正在尝试制作一个自定义损失函数,它根据预测值和实际值的范围返回不同的值。但是我无法比较这些值,因为变量是张量,而且我找不到获取它们唯一元素数值的方法(我的输出是一维的)。我认为这将是一项简单的任务,但我尝试了很多东西(转换为 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,取而代之的是 'float' 类型的 0.5。

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

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

【问题讨论】:

  • 请在 Stack Overflow 上包含可重现的代码,而不是在第三方网站上。

标签: python tensorflow keras deep-learning tensor


【解决方案1】:

转换为浮动:

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)

【讨论】:

  • 它仍然显示OperatorNotAllowedInGraphError: using a `tf.Tensor` as a Python `bool` is not allowed: AutoGraph did convert this function. This might indicate you are trying to use an unsupported feature.
  • 同样的错误。如果我将条件简化为if y &gt; tf.constant(0.5):,它会显示TypeError: 'retval_' has dtype int32 in the main branch, but dtype float32 in the else branch
  • @Raphael 查看编辑后的答案(在零后添加点)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-31
  • 2019-01-02
  • 2018-03-13
  • 2020-02-03
  • 1970-01-01
  • 2021-01-25
  • 1970-01-01
相关资源
最近更新 更多