在 tensorflow 中,给定特定的列列表,我尝试用零列填充张量。
如何在 tensorflow 中实现它?我尝试使用 tf.assign
或 tf.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/