假设我有两个张量:
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。 有任何线索吗?
谢谢
答案 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.]]