【问题标题】:Computing gradients of a multi-output model in Keras giving conversion to Tensorflow DType error在 Keras 中计算多输出模型的梯度,将其转换为 Tensorflow DType 错误
【发布时间】:2020-12-24 05:31:03
【问题描述】:

我在 Keras 中有一个多输出模型(准确地说是 18 个输出),每个输出都有一个损失函数。我试图在 fast-RCNN 中模仿区域建议网络。在训练之前,我想确保我的模型的梯度是有序的,我有一个如下的 sn-p:

with tf.GradientTape() as tape:
    loss = RegionProposalNetwork.evaluate(first_batch)[0]
    t = tape.watched_variables()
grads = tape.gradient(loss, RegionProposalNetwork.trainable_variables)
print(grads)

变量first_batch是通过使用take()从一个tf.data对象获得的。功能。返回值 loss 是一个大小为 19 的数组,其中 loss[0] 是所有损失函数的总和,也就是整体损失。在能够打印渐变数组之前,我收到错误消息/跟踪:

Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.2\plugins\python-ce\helpers\pydev\pydevd.py", line 1448, in _exec
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.2\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/James/PycharmProjects/Masters/models/MoreTesting.py", line 469, in <module>
    grads = tape.gradient(loss, RegionProposalNetwork.trainable_variables)
  File "C:\Users\James\Anaconda3\envs\masters\lib\site-packages\tensorflow\python\eager\backprop.py", line 1034, in gradient
    if not backprop_util.IsTrainable(t):
  File "C:\Users\James\Anaconda3\envs\masters\lib\site-packages\tensorflow\python\eager\backprop_util.py", line 30, in IsTrainable
    dtype = dtypes.as_dtype(dtype)
  File "C:\Users\James\Anaconda3\envs\masters\lib\site-packages\tensorflow\python\framework\dtypes.py", line 650, in as_dtype
    (type_value,))
TypeError: Cannot convert value 29.614826202392578 to a TensorFlow DType.

其中 float 29.614826202392578 是对模型评估函数的调用的总体损失。我不确定这个错误是什么意思。作为参考,所有输入数据类型和中间层结果都是 tf.float32 值的张量。任何见解都值得赞赏。

编辑:如果我尝试使用tf.convert_to_tensor 将损失转换为张量,我将不再收到错误,但返回的梯度都是无。我已经测试过我的模型权重更新会调用fit(),所以出了点问题。

【问题讨论】:

    标签: python keras tensorflow2.0


    【解决方案1】:

    我遇到的问题是返回值描述为here

    返回标量测试损失(如果模型有单个输出并且没有 指标)或标量列表(如果模型有多个输出和/或 指标)。属性 model.metrics_names 会给你显示 标量输出的标签。

    不是张量。同样 model.predict() 将不起作用,因为结果是一个 numpy 数组,破坏了梯度计算。为了计算梯度,如果我只是简单地在测试输入数据上调用模型,然后计算相对于真实值的损失函数,那么循环就可以工作,a.k.a

    with tf.GradientTape() as tape:
         model_output = model(input)
         loss = loss_fn(output, model_output)
    gradients = tape.gradient(loss, model.trainable_variables)
    
    # And if you are using a generator, 
    batch = data_iterator.get_next()
    input = batch[0]
    output = batch[1]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      • 2017-08-14
      • 1970-01-01
      • 2021-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多