Tensorflow - 有条件地为张量赋值
Tensorflow - Conditionally assign value to a 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]。
谢谢,
您可以执行以下操作。这应该适用于 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)
我有 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]。
谢谢,
您可以执行以下操作。这应该适用于 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)