首页 > 解决方案 > tflite图中Conv2D的奇怪输出

问题描述

我有一个 tflite 图形片段,其在附图中描述在此处输入图像描述

我需要调试它的行为,并且在第一步我得到了相当令人费解的结果。当我在第一个 Conv2D 之后输入零张量作为输入时,我希望得到一个仅包含来自 Conv2D 偏差的值的张量(因为所有内核元素都乘以零),但是我有一个由一些随机数据组成的张量,这里是代码片段:

def test_graph(path=PATH_DEFAULT):
    interp = tf.lite.Interpreter(path)
    interp.allocate_tensors()

    input_details = interp.get_input_details()
    in_idx = input_details[0]['index']

    zeros = np.zeros(shape=(1, 256, 256, 3), dtype=np.float32)
    interp.set_tensor(in_idx, zeros)
    interp.invoke()

    # index of output of first conv2d operator is 3 (see netron pic)
    after_conv_2d = interp.get_tensor(3)

    # shape of bias is just [count of output channels]
    n, h, w, c = after_conv_2d.shape

    # if we feed zeros as input, we can expect that the only values we get are the values of bias
    # since all kernel elems in that case are multiplied by zeros

    uniq_vals_cnt = len(np.unique(after_conv_2d))
    assert uniq_vals_cnt <= c, f"There are {uniq_vals_cnt} in output, should be <= than {c}"

输出:

AssertionError: There are 287928 in output, should be <= than 24

有人可以帮助我解决我的误解吗?

标签: tensorflowmachine-learningtensorflow-lite

解决方案


似乎我假设我可以从解释器获得任何中间张量是错误的,我们只能为输出做这件事,即使解释器不会引发错误,甚至为与非输出张量相关的索引提供正确形状的张量。

调试此类图的一种方法是制作所有张量输出,但似乎最简单的方法是将tflite文件转换为pbwith toco,然后再转换pbtflite指定的新输出。这种方式并不理想,因为在 1.9 之后删除toco了对转换的支持,tflite -> pb并且使用之前的版本可能会在某些图表上中断(在我的情况下它会中断)。

更多内容在这里: tflite: get_tensor on non-output tensors give random values


推荐阅读