python - tensorflow boolean_mask 逆?

标签 python tensorflow

我有一个根据 boolean_mask 拆分的张量:

with tf.Session() as sess:
    boolean_mask = tf.constant([True, False, True, False])
    foo = tf.constant([[1,2],[3,4],[5,6],[7,8]])   
    true_foo = tf.boolean_mask(foo, boolean_mask, axis=0)
    false_foo = tf.boolean_mask(foo, tf.logical_not(boolean_mask), axis=0)
    print(sess.run((true_foo, false_foo)))

输出:

(array([[1, 2],
        [5, 6]], dtype=int32), 
 array([[3, 4],
        [7, 8]], dtype=int32))

我对 true_foofalse_foo 做了一些操作,然后我想将它们按原来的顺序放回去:

    true_bar = 2*true_foo
    false_bar = 3*false_foo
    bar = tf.boolean_mask_inverse(boolean_mask, true_bar, false_bar)
    print(sess.run(bar))

应该输出:

array([[ 2, 4],
       [ 9,12],
       [10,12],
       [21,24]], dtype=int32)

最佳答案

类似于您自己的解决方案,但使用 tf.scatter_nd

true_mask = tf.cast(tf.where(boolean_mask), tf.int32)
false_mask = tf.cast(tf.where(~boolean_mask), tf.int32)
t_foo = tf.scatter_nd(true_mask, true_bar, shape=tf.shape(foo))
f_foo = tf.scatter_nd(false_mask, false_bar, shape=tf.shape(foo))
res = t_foo + f_foo
# array([[ 2,  4],
#        [ 9, 12],
#        [10, 12],
#        [21, 24]], dtype=int32)

基本上,您可以将 true_barfalse_bar 分散到两个不同的张量,然后将它们相加。

关于python - tensorflow boolean_mask 逆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58564613/

相关文章:

python - Django 模型表单设置 POST 但不保存

javascript - 在 Django 中进行 Javascript 验证后发布到 Python View

python - Pandas 过滤和组合

tensorflow - 我们如何使用 tf.image.encode_jpeg 在 TensorFlow 中写出图像?

python - 如何控制使用 tfrecords 和 steps_per_epoch 读取哪些样本

tensorflow - TensorFlow SparseCategoricalCrossentropy 如何工作?

python - 测试对象来自哪个模块而不是它是哪种类型

导入库时 Python StanfordNLP 包错误

python - 无法加载 native TensorFlow 运行时。原因 : Image not found. 我做错了什么?

tensorflow - 如何使用多个model_spec创建单个PredictRequest()?