在tensorflow中,如何将动态形状应用于scatter_nd

当我使用具有动态形状的输入张量时,出现以下错误:


  ValueError:无法将部分已知的TensorShape转换为Tensor:
  (20,?)


这是我使用的功能。当tensor具有静态形状时可以使用。但是使用动态形状(例如(?, 7)),它会失败。

def tf_zero_pad_columns(tensor, columns_list, num_output_columns):
    assert(tensor.shape.as_list()[1] == len(columns_list))
    assert(num_output_columns >= len(columns_list))

    tensor = tf.transpose(tensor)
    columns = tf.constant(np.array([columns_list]).T.astype('int32'))
    shape=tf.TensorShape((num_output_columns, tensor.get_shape()[1]))
    scattered = tf.scatter_nd(columns, tensor, shape=shape)
    return tf.transpose(scattered)


我还尝试用tensor.get_shape()[1]替换-1,但这在训练过程中会产生不同的错误:


  InvalidArgumentError:维度-1必须> = 0 [[[Node:
  lambda_40 / ScatterNd ....




编辑:

具有动态形状的示例输入(这会重现错误):

tensor = tf.placeholder(tf.float32, shape=(None, 7))
tf_zero_pad_columns(tensor, [11,12,13,4,5,6,7], 20)


具有静态形状的示例输入:

import numpy as np
tensor_np = np.tile(range(7), (4, 1)) + np.array(range(4))[:, None]
tensor = tf.constant(tensor_np)


tf_zero_pad_columns(tensor, [11,12,13,4,5,6,7], 20)


输出为:

array([[0, 0, 0, 0, 3, 4, 5, 6, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 4, 5, 6, 7, 0, 0, 0, 1, 2, 3, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 5, 6, 7, 8, 0, 0, 0, 2, 3, 4, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 6, 7, 8, 9, 0, 0, 0, 3, 4, 5, 0, 0, 0, 0, 0, 0]])

最佳答案

这对我有用:

def tf_zero_pad_columns(tensor, columns_list, num_output_columns):
    assert(tensor.shape.as_list()[1] == len(columns_list))
    assert(num_output_columns >= len(columns_list))

    tensor = tf.transpose(tensor)
    columns = tf.constant(np.array([columns_list]).T.astype('int32'))
    tensor_shape = tf.shape(tensor)[1]
    scattered = tf.scatter_nd(columns, tensor, shape=(num_output_columns, tensor_shape))
    return tf.transpose(scattered)

关于python - 如何使用 tensorflow `scatter_nd`应用动态形状,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54505292/

10-08 22:01