【问题标题】:Multiple if-else conditions in tensorflow张量流中的多个if-else条件
【发布时间】:2017-10-11 22:31:15
【问题描述】:

我有一个形状为 (1) 的浮点张量,其值介于 0.0 和 1.0 之间。 我想'bin'这个张量中的范围,如:

if 0.0 < x < 0.2: 
  return tf.Constant([0])
if 0.2 < x < 0.4: 
  return tf.Constant([1])
if 0.4 < x < 0.6: 
  return tf.Constant([2])
if 0.6 < x: 
  return tf.Constant([3])

不知道怎么做!

【问题讨论】:

    标签: tensorflow


    【解决方案1】:

    您没有解释边界点(0.2、0.4、...)会发生什么,也没有显示 x > 0.6 时要输出什么,所以我的假设是:

    • 封闭的开放区间; a
    • 相同的 bin 过程一直持续到 1,步长为 0.2

    对于这样一个简单的情况,您不需要 if else 条件(也会很慢)。您可以通过数学和铸造来实现它:

    import tensorflow as tf
    
    x = tf.constant(0.25)
    res = tf.cast(5 * x, tf.int32)
    with tf.Session() as sess:
        print sess.run(res)
    

    【讨论】:

      【解决方案2】:

      试试 tg.logical_and 以下示例可能会有所帮助

      b = tf.constant([5,2,-3,1])
      c1 = tf.greater(b,0) # b>0
      c2 = tf.less(b,5) # b<5
      c_f = tf.logical_and(c1, c2) # 0 < b < 5
      sess=tf.Session()
      sess.run(c_f)
      

      【讨论】:

      • 如何返回一个值(张量)?在问题中,代码返回一个转换为张量值的常量。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-05
      • 1970-01-01
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 2018-09-24
      相关资源
      最近更新 更多