问题
Does tensorflow provide a way to create a zero-tensor while replacing a general slice by another one? In particular, I need to assign 2D blocks in a matrix-tensor. Here's an example of what I need to achieve:
Given a tensor of variable shape, eg.
[1 2 3
4 5 6],
and another tensor defining the slice, eg.
[0 0 0 0 0
0 1 1 1 0
0 1 1 1 0],
the new tensor should look as follows:
[0 0 0 0 0
0 1 2 3 0
0 4 5 6 0].
I know there's scatter_nd
, but it seems like it can only 'replace' values along a full axis. Do I miss any operation or is there any workaround to achieve this?
回答1:
You can use assign
on the appropriate slice of y
:
import numpy as np
import tensorflow as tf
x = tf.constant([[1,2,3],[4,5,6]])
y = tf.Variable([[0,0,0,0,0],[0,1,1,1,0],[0,1,1,1,0]])
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
z = y[1:,1:4].assign(x)
z.eval()
# returns
# array([[0, 0, 0, 0, 0],
# [0, 1, 2, 3, 0],
# [0, 4, 5, 6, 0]])
EDIT
Same thing dynamically (here for the position only)
import numpy as np
import tensorflow as tf
x = tf.constant([[1,2,3],[4,5,6]])
y = tf.Variable([[0,0,0,0,0],[0,1,1,1,0],[0,1,1,1,0]])
pos = tf.placeholder(tf.int32, shape=(2,))
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
z = y[pos[0]:2+pos[0],pos[1]:3+pos[1]].assign(x)
z.eval({pos: [1,1]})
来源:https://stackoverflow.com/questions/44888587/assign-2d-block-slice-in-tensorflow