2017-07-20 38 views
1

例如,在[0, 8]一些应该返回0,在(8, 16]回报1,在(16, 24]应该返回2等..如何在TensorFlow中将连续的数字转换为几个类?

然后,如果我有一个张量[2,3,9,18],我怎样才能在TensorFlow输出列表[0, 0, 1, 2]

谢谢。

编辑:

现在我用tf.case这个需求

c0 = lambda: tf.constant(0.) 
c1 = lambda: tf.constant(1.) 
c2 = lambda: tf.constant(2.) 
c3 = lambda: tf.constant(3.) 

cases = lambda x: {tf.less(x, 9.): c0, tf.less(x, 18.): c1, tf.less(x, 24.): c2} 
condition = lambda x: tf.case(cases(x), default=c3, exclusive=False, name='condition') 
output = tf.map_fn(lambda x: condition(x), input, name='prediction') 

回答

0

这个问题可能在许多不同的方式来解决这取决于范围列表有多大,或者如果他们遵循一种数学模式。如果它是一个简单的用例,我会稍微修改你的解决方案,以便更清楚。

(1)

def func(x): 
    if x<=8: 
     return 'A' 
    elif 8 < x <= 16: 
     return 'B' 
    elif 16 < x <= 24: 
     return 'C' 
    else: 
     return 'D' 

如果范围按照一定的数学模式类似的例子中,你 可以像下面

(2)

classes = "0ABCD" 
def clamp(num): 
    return classes[ceil(num/8)] # TODo error checking 

或者有很多范围,那么你可以将排序的范围存储在列表中并进行二分搜索。 (3)

ranges = [(0,8,'A'),(8, 16, 'B'), ...] 
#TODO use binary search from.. https://docs.python.org/3.6/library/bisect.html 
+1

Thk!我使用第一种方法,并使用'tf.map_fn',我不知道有些'API'可以做到这一点。第二种方法对此很有帮助,但实际上这个区域并不统一,可能是'0,3,8,15,16'...... – danche

相关问题