【问题标题】:Is there a way to do the same thing in tensorflow as it's done below in numpy?有没有办法在 tensorflow 中做与下面在 numpy 中所做的相同的事情?
【发布时间】:2018-03-16 15:06:31
【问题描述】:

通过使用 numpy,我可以索引一个数组,如下所示

x[mask==1]

假设xmask 都是numpy 数组并且mask 只包含10

现在我将xmask 都作为Tensors 并想模仿上述行为。我该怎么办?

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    使用boolean_mask

    示例

    x = tf.constant([[1,2],[3,4]])
    mask = tf.constant([[1,0],[0,1]])
    tf.boolean_mask(x, tf.equal(mask, 1)).eval()
    # array([1, 4])
    

    【讨论】:

    • mask是未知形状的占位符时,我收到一条错误消息说Number of mask dimensions must be specified, even if some dimensions are None. E.g. shape=[None] is ok, but shape=None is not.我该如何解决?
    • @SherwinChen 你不能使用完全未知的形状。必须知道占位符的维度,见stackoverflow.com/questions/48978984/…
    • 谢谢你,我已经摆脱了它:)
    【解决方案2】:

    这会给你一个布尔掩码

     import tensorflow as tf
     a = tf.Variable( [1,2,3,1] )   
     comparison = tf.equal( a, tf.constant( 1 ) )  
     start_op = tf.global_variables_initializer()    
     with tf.Session() as session:
       session.run(tart_op)
    
      print(session.run(comparison))
    
    [ True False False  True]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-03
      • 1970-01-01
      • 2022-08-15
      • 2016-07-31
      • 1970-01-01
      • 2012-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多