首页 > 解决方案 > 生成部分已知的张量 Tensorflow

问题描述

所以我在 Tensorflow 上做了一个自定义层。在调用函数中,我收到了所需的输出形状。基本上,我的最后几行代码实际上是:

desired_output_shape_with_batch = tf.concat([[tf.shape(inputs_values)[0]], output_shape], axis=0)
ret = tf.reshape(ret, shape=desired_output_shape_with_batch)
return ret

我使用 concat: 的第一个维度tf.shape(inputs_values)[0]作为批量大小,直到现在我还想制作能够更改的所需输出形状。

例如 (None, None, 3) 所以我可以接受不同的 RGB 图像。

但是, concat 函数说:ValueError: Cannot convert a partially known TensorShape to a Tensor: (None, None, 3)

这不是问题我可以使用该is_fully_defined()方法并在函数的开头检查形状是否完全定义,如果不只是返回部分定义的张量 shape (None, None, None, 3),但我如何创建这个部分定义的张量?

基本上,我的想法是:

def call(inputs, **kwargs):
    inputs_values, output_shape = inputs
    if tf.TensorShape(output_shape).is_fully_defined():
        # do my stuff
        return ret
    else:
        # output shape will be a list or set with some None values
        return tf.Tensor(shape=(None,) + output_shape)

我怎样才能做到这一点?如果有更好的实践方法可以做到这一点,我也愿意提供建议。

这个问题类似于在创建层时处理符号张量的无维度,这实际上是我想要的同一层,这一次,能够对desired_output_shape模型的构造有一个未知数。

标签: pythontensorflow

解决方案


推荐阅读