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

标签 python python-3.x tensorflow

在 tensorflow 中,给定特定的列列表,我尝试用零列填充张量。

如何在 tensorflow 中实现它?我尝试使用 tf.assigntf.scatter_nd,但遇到了一些错误。

这是一个简单的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.]]

我尝试在 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)

但这会产生以下错误:

TypeError: can only concatenate list (not "int") to list

我还尝试使用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)

但这会产生以下错误:

InvalidArgumentError: Inner dimensions of output shape must match inner dimensions of updates shape. Output: [3,7] updates: [3,2] [Op:ScatterNd]

最佳答案

这是一个解决方案:

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))

关于python - 给定列的*列表*,如何用零列填充 TF 张量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54481467/

相关文章:

python - 索引错误 : too many indices for np. 数组

python - 使用 timedelta 时小数位太多

python - 同时使用 2 个 GPU 进行不同的 TensorFlow\Python

python - 鉴于两个项目不能在同一个列表中,如何获得列表的所有组合?

python - 匹配两个具有最大重复次数的唯一字符。如何使用正则表达式提取它?

python - Python 中的正则表达式和格式化

python - “ImageDataGenerator”对象没有属性 'image_data_generator'

python - 图形中的重复节点名称 : 'conv2d_0/kernel/Adam'

python - 如何在代码中转换速度?

python - 如果在字符串中找到字符串,则无法更新变量