Tensorflow-有条件地将值分配给张量

时间:2019-12-02 22:43:54

标签: python tensorflow tensor

我有2个张量。

t1 = tf.constant([b'hi', b'#hh', b'hello', 'there', '#ii'], dtype=tf.string)

t2 = tf.constant([1,2,3], dtype = tf.int64)

如何替换t1中以#初始化的元素为0,t1中的所有其他元素为t2中的数字?

具体来说,输出应为[1、0、2、3、0]。

谢谢

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作。 TF1和TF2(已测试)都可以使用。在TF1中,只需执行sess.run(res)即可得到结果。

t1 = tf.constant(['hi', '#hh', 'hello', 'there', '#ii'], dtype=tf.string)
t2 = tf.constant([1,2,3], dtype = tf.int32)

# Create mask of the ids we want to change
mask = tf.logical_not(tf.strings.regex_full_match(t1,'^#.*'))
idx = tf.cast(mask, dtype=tf.int32)
# Get the cumulative sum [1, 1, 2, 3, 3]
cumsum = tf.cumsum(idx)
# Do a where and replace the unwanted ids with zeros
res = tf.where(mask, y=tf.zeros_like(t1, dtype=tf.int32), x=cumsum)