如何通过单元测试检查梯度计算

2024-04-20 02:59:00 发布

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

我正在尝试对自定义层进行单元测试。编写前馈测试非常简单,但是我不知道如何实现梯度测试。你知道吗

我发现tensorflow测试包中有一个名为compute_gradient的函数,但是我找不到任何关于如何使用它的资源。文档基本上说它计算梯度(雅可比矩阵),这是我想要的,但是当我尝试使用它时,我得到EagerTensor is not callable

这是失败的代码:

class LayerGradientTest(tf.test.TestCase):
    def test_gradient(self):
        with self.test_session():
            input_tensor = [...]
            expected_output = [...]
            expected_gradients = [...]
            test_layer = MyLayer()
            output_tensor = test_layer(tf.Variable(input_tensor))
            grad_computed = tf.test.compute_gradient(output_tensor, expected_output)
            self.assertAllEqual(grad_computed, expected_gradients)

我希望测试要么通过要么失败的断言,但我得到了一个答案 TypeError: 'tensorflow.python.framework.ops.EagerTensor' object is not callable来自compute_gradient

编辑: 当然梯度需要损失函数,我是个白痴。。。但产出仍然是毫无意义的。我现在使用以下代码:

function = tf.losses.mean_squared_error
grad_computed = tf.test.compute_gradient(function, [output_tensor, expected_output])

输入到我的图层的形状是(1,2,2,3)和(1,2,2,2),但是渐变是一个包含4个12x4矩阵的zip对象,但是由于我的图层中没有参数,我希望在输入时得到错误值。如果我又把事情搞砸了,请纠正我。只是澄清一下,我的层只是转换数据,因此它本身没有梯度,但必须正确地向后传播它们。你知道吗


Tags: 函数testselfoutputtftensorflow矩阵expected
1条回答
网友
1楼 · 发布于 2024-04-20 02:59:00

检查是否启用了急切执行,如果没有,请在导入中尝试下面的代码

import tensorflow as tf
tf.enable_eager_execution()

相关问题 更多 >