简体   繁体   English

给定列的*列表*,如何用零列填充 TF 张量

[英]How to pad a TF Tensor with zero columns, given a *list* of columns

In tensorflow, I am trying to pad a tensor with zero columns, given a specific list of columns.在 tensorflow 中,给定特定的列列表,我试图用零列填充张量。

How can I implement it in tensorflow?如何在 tensorflow 中实现它? I tried using tf.assign or tf.scatter_nd , but encountered some errros.我尝试使用tf.assigntf.scatter_nd ,但遇到了一些错误。

Here is a simple numpy implementation这是一个简单的numpy实现

a_np = np.array([[1, 2],
                 [3, 4], 
                 [5, 6]])
columns = [1, 5]
a_padded = np.zeros((3, 7))
a_padded[:, columns] = a_np
print(a_padded)

## output ##

[[0. 1. 0. 0. 0. 2. 0.]
 [0. 3. 0. 0. 0. 4. 0.]
 [0. 5. 0. 0. 0. 6. 0.]]

I tried to do the same in tensorflow:我试图在 tensorflow 中做同样的事情:

a = tf.constant([[1, 2],
                 [3, 4], 
                 [5, 6]])
columns = [1, 5]
a_padded = tf.Variable(tf.zeros((3, 7)))
a_padded[:, columns].assign(a)

But this produces the following error:但这会产生以下错误:

TypeError: can only concatenate list (not "int") to list类型错误:只能将列表(不是“int”)连接到列表

I also tried using tf.scatter_nd :我也尝试使用tf.scatter_nd

a = tf.constant([[1, 2],
                 [3, 4], 
                 [5, 6]])
columns = [1, 5]
shape = tf.constant((3, 7))
tf.scatter_nd(columns, a, shape)

But this produces the following error:但这会产生以下错误:

InvalidArgumentError: Inner dimensions of output shape must match inner dimensions of updates shape. InvalidArgumentError:输出形状的内部尺寸必须与更新形状的内部尺寸匹配。 Output: [3,7] updates: [3,2] [Op:ScatterNd]输出:[3,7] 更新:[3,2] [Op:ScatterNd]

Here is a solution:这是一个解决方案:

tf.reset_default_graph()
a = tf.constant([[1, 2], [3, 4], [5, 6]], dtype=tf.int32)
columns = tf.constant([1, 5], dtype=tf.int32)
a_padded = tf.Variable(tf.zeros((3, 7), dtype=tf.int32))
indices = tf.stack(tf.meshgrid(tf.range(tf.shape(a_padded)[0]), columns, indexing='ij'), axis=-1)
update_cols = tf.scatter_nd_update(a_padded, indices, a)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(update_cols))

(OP here) I managed to find a solution using tf.scatter_nd . (OP here)我设法使用tf.scatter_nd找到了解决方案。 The trick was to align the dimensions of a, the columns and the output shape.诀窍是对齐 a、列和输出形状的尺寸。

a_np = np.array([[1, 2],
                 [3, 4], 
                 [5, 6]])

# Note the Transpose on every line below
a = tf.constant(a_np.T) 
columns = tf.constant(np.array([[1, 5]]).T.astype('int32'))
shape = tf.constant((7, 3))
a_padded = tf.transpose(tf.scatter_nd(columns, a, shape))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM