根据来自另一个张量的值将值分配给张量

时间:2019-06-11 13:22:43

标签: python-3.x tensorflow keras

假设我有两个张量:

import keras as K
import tensorflow as tf

A=K.zeros((4,4))    
T=K.constant([0,1,2,2]) 

#do something

#expected result: 1 starting at the index in tensor T
'''
array([[1, 1, 1, 1],      <-- 1 starting at index(column) 0
   [0, 1, 1, 1],          <-- 1 starting at index(column) 1
   [0, 0, 1, 1],          <-- 1 starting at index(column) 2
   [0, 0, 1, 1]])         <-- 1 starting at index(column) 2

'''

这个想法是从张量T中包含的索引开始为张量A分配1。 有任何线索吗?

谢谢

1 个答案:

答案 0 :(得分:2)

您需要tf.sequence_mask

import keras.backend as K
import tensorflow as tf

A= K.zeros((4,4))
T= K.constant([0,1,2,2])

mask = tf.sequence_mask(T,A.shape[-1])
# [[False False False False]
#  [ True False False False]
#  [ True  True False False]
#  [ True  True False False]]
result = tf.where(mask,A,tf.ones_like(A))

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(result))

[[1. 1. 1. 1.]
 [0. 1. 1. 1.]
 [0. 0. 1. 1.]
 [0. 0. 1. 1.]]