计算Keras中多输出模型的梯度,并将其转换为Tensorflow数据类型错误

2024-04-19 01:47:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Keras的多输出模型(精确地说是18个输出),每个输出都有一个损失函数。我试图在更快的RCNN中模仿区域建议网络。在培训之前,我想确保我的模型的梯度是有序的,我有一个片段,如下所示:

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.

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

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


Tags: inpy模型tfaslineusersfile
1条回答
网友
1楼 · 发布于 2024-04-19 01:47:55

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

Return Scalar test loss (if the model has a single output and no metrics) or list of scalars (if the model has multiple outputs and/or metrics). The attribute model.metrics_names will give you the display labels for the scalar outputs.

不是张量。类似地,model.predict()也不起作用,因为结果是一个numpy数组,破坏了梯度计算。为了计算梯度,如果我只是调用测试输入数据上的模型,然后计算关于地面真值的损失函数,即

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]

相关问题 更多 >