Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在tensorflow中张量的某些索引处插入某些值?_Python_Tensorflow_Keras_Mutable_Tensor - Fatal编程技术网

Python 如何在tensorflow中张量的某些索引处插入某些值?

Python 如何在tensorflow中张量的某些索引处插入某些值?,python,tensorflow,keras,mutable,tensor,Python,Tensorflow,Keras,Mutable,Tensor,假设我有一个形状为100x1的张量输入,另一个位置为20x1的张量和形状为100x1的索引张量。索引张量表示输入的位置,我想在该位置插入中的值。索引张量只有20个真值,其余值为假。我试图在下面解释所需的操作。 如何使用tensorflow实现此操作 assign操作仅适用于tf.Variable,而我希望将其应用于tf.nn.rnn的输出 我知道一个人可以使用tf.scatter\u nd,但它要求inplace和index\u tensor具有相同的形状 我想用它的原因是,我从rnn中得到一个

假设我有一个形状为100x1的张量
输入
,另一个位置为20x1的张量
和形状为100x1的索引张量。
索引张量
表示
输入
的位置,我想在该位置插入
中的值。
索引张量
只有20个真值,其余值为假。我试图在下面解释所需的操作。 如何使用tensorflow实现此操作

assign
操作仅适用于
tf.Variable
,而我希望将其应用于
tf.nn.rnn
的输出

我知道一个人可以使用
tf.scatter\u nd
,但它要求
inplace
index\u tensor
具有相同的形状

我想用它的原因是,我从rnn中得到一个输出,然后我从中提取一些值,并将它们输入到某个稠密层,这个稠密层的输出,我想插入到我从rnn运算中得到的原始张量中。由于某些原因,我不想对rnn的整个输出应用稠密层操作,如果我不将稠密层的结果插入rnn的输出中,那么稠密层是无用的


任何建议都将非常感谢。

因为你的张量是不可变的,你不能给它赋值,也不能在适当的地方修改它。您需要做的是使用标准操作修改其值。以下是您如何做到这一点:

input_array = np.array([2, 4, 7, 11, 3, 8, 9, 19, 11, 7])
inplace_array = np.array([10, 20])
indices_array = np.array([0, 0, 1, 0, 0, 0, 1, 0, 0, 0])
# [[2], [6]] 
indices = tf.cast(tf.where(tf.equal(indices_array, 1)), tf.int32)
# [0, 0, 10, 0, 0, 0, 20, 0, 0, 0]
scatter = tf.scatter_nd(indices, inplace_array, shape=tf.shape(input_array))
# [1, 1, 0, 1, 1, 1, 0, 1, 1, 1]
inverse_mask = tf.cast(tf.math.logical_not(indices_array), tf.int32)
# [2, 4, 0, 11, 3, 8, 0, 19, 11, 7]
input_array_zero_out = tf.multiply(inverse_mask, input_array)
# [2, 4, 10, 11, 3, 8, 20, 19, 11, 7]
output = tf.add(input_array_zero_out, tf.cast(scatter, tf.int32))