python中tf.boolean_mask()函数的使用

  tf.boolean_mask() 函数的作用是通过布尔值对指定的列的元素进行过滤。

  • 语法结构
boolean_mask(tensor, mask, name="boolean_mask", axis=None)

其中,tensor:被过滤的元素
   mask:一堆bool值,它的维度不一定等于tensor
   return:mask为true对应的tensor的元素
   当tensormask维度一致时,返回一维

  • 1-D example
    examples1: >>> import numpy as np
           >>> import tensorflow as tf
           >>> a = [1, 2, 3, 4]
           >>> mask = np.array([True, True, False, False])   # mask 与 a 维度相同
           >>> b = tf.boolean_mask(a, mask)
           >>> with tf.Session() as sess:
               print(sess.run(b))
               print(b.shape)

        [1 2]
        (?,)

  • 2-D example
    examples2: >>> import numpy as np
           >>> import tensorflow as tf
           >>> a = [[1, 2], [3, 4], [5, 6]]
           >>> mask = np.array([True, False, True])   # mask 与 a 维度不同
           >>> b = tf.boolean_mask(a, mask)
           >>> with tf.Session() as sess:
               print(sess.run(b))
               print(b.shape)

         [[1 2]
          [5 6]]
         (?, 2)

  • 3-D example
    examples3: >>> import numpy as np
           >>> import tensorflow as tf
           >>> a = tf.constant([
                     [[2, 4], [4, 1]],
                     [[6, 8], [2, 1]]], tf.float32)
           >>> mask = a > 2   # mask 与 a 维度相同
           >>> b = tf.boolean_mask(a, mask)
           >>> with tf.Session() as sess:
               print(sess.run(a))
               print(sess.run(mask))
               print(sess.run(b))
               print(b.shape)

          [[[2. 4.]
          [4. 1.]]

           [[6. 8.]
          [2. 1.]]]

          [[[False True]
          [ True False]]

           [[ True True]
          [False False]]]

            [4. 4. 6. 8.]
            (?,)

  上面的shape有如下的规则:
  假设 tensor.rank=4,维度为(m,n,p,q),则
    (1)当mask.shape=(m,n,p,q),结果返回(?,),表示所有维度都被过滤
    (2)当mask.shape=(m,n,p),结果返回(?,q),表示 q 维度没有过滤
    (3)当mask.shape=(m,n),结果返回(?,p,q),表示 p,q 维度没有过滤
    (4)当mask.shape=(m),结果返回(?,n,p,q),表示 n,p,q 维度没有过滤

  tensorflow 使用一种叫tensor的数据结构去展示所有的数据,我们可以把tensor看成是n维的array或者list。在tensorflow的各部分图形间流动传递的只能是tensor。
  tensorflow用3种方式描述一个tensor的维数:rank、shape、dimension number (维数),所以shape和rank的意思的一样的,只是表达的形式不同。

rankshapedimension
0[ ]0 维
1[ D0 ]1 维
2[ D0, D1 ]2 维
n[ D0, D1, …, Dn-1 ]n 维
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值