将张量数据裁剪到边界体积

问题描述

我有 2 个关于 tensorflow 2.0 的问题,重点是 tensorflow 如何处理其操作图中的组合条件测试。

任务:将大量数据点切成块,并将索引存储到属于该体积的样本中(不是样本本身)。

我的初始方法:循环所有元素并收集“边界体积”内数据点的索引。无论我如何重新排列坐标上的比较,这都很慢。

    # X.shape == [elements,features]
    # xmin.shape == xmax.shape == [features]

    def getIndices(X,xmin,xmax):
        i = 0
        indices = tf.zero(shape[0],dtype = tf.int32)
        for x in X:
            if (x[0] > xmin[0]):
                if (x[1] > xmin[1]):
                    if (x[2] <= xmax[2]):

                        # ...and so on...

                        indices = tf.concat([indices,i],axis = 0)
            i = i + 1
        return indices

然后我想出了生成布尔张量的想法,并在逻辑上“和”它们以获得我需要的元素的 indices。速度要快得多,如下一个示例所示:

    # X.shape == [elements,xmax):
        # example of 3 different conditions to clip to (a part of) the bounding volume 
        # X is the data and xmin and xmax are tensors containing the bounding volume

        c0 = (X[:,0] >   xmin[0])
        c1 = (X[:,1] >   xmin[1]) # processing all elements
        c2 = (X[:,2] <=  xmax[2]) # idem

        # ... there Could be many more conditions,you get the idea..

        indices = tf.where(tf.math.logical_and(c1,tf.math.logical_and(c2,c3) )

        return indices

    #    ...

    indices = getIndices(X,xmax)
    trimmedX = tf.gather(X,indices)

这段代码产生了正确的结果,但我想知道它是否最优

一个问题是关于日程安排的:

保存操作的张量流图是否会剔除(块) 条件测试是否知道已经测试过的一些(块)元素 False。由于 logical_and 结合了逻辑 条件,对这些元素的后续条件测试不会 永远产生True

事实上,在上面的例子中,c1c2 是针对可能已经从集合中排除的元素提出问题 c0。特别是当您有大量元素要测试时,即使在并行硬件平台上,这也可能是浪费时间

那么,如果我们根据先前测试的结果级联测试会怎样?虽然看起来是一个解决的问题,但这个解决方案是不正确的,因为最终的 indices 张量将引用子集 _X,而不是整个集合 X

    # X.shape == [elements,xmax):
        c0 = (X[:,0] >   xmin[0])
        indices = tf.where(c0)
        _X = tf.gather(X,indices)

        c1 = (_X[:,1] >   xmin[1]) # processing only trimmed elements
        indices = tf.where(c1)
        _X = tf.gather(_X,indices)

        c2 = (_X[:,2] <=  xmax[2]) # idem
        indices = tf.where(c2)
        return indices

    ...
    indices = getIndices(X,indices)  # fails: indices refer to a trimmed subset,not X

我当然可以通过简单地扩展 X 来“解决”这个问题,这样每个元素也可以在原始列表中包含自身的索引,然后像以前一样继续。

所以我的第二个问题是关于功能的:

tf 有没有办法让 GPU/张量基础设施提供 簿记无需在此表面上花费内存/时间 简单的问题?

解决方法

这将返回大于 minimum 且小于 maximum 的所有索引,当它们与 X 具有相同数量的特征时

import tensorflow as tf

minimum = tf.random.uniform((1,5),0.,0.5)
maximum = tf.random.uniform((1,0.5,1.)

x = tf.random.uniform((10,5))

indices = tf.where(
    tf.logical_and(
        tf.greater(x,minimum),tf.less(x,maximum)
        )
    )
<tf.Tensor: shape=(22,2),dtype=int64,numpy=
array([[0,3],[0,4],[1,1],2],[3,[4,0],[5,[6,[7,[8,[9,4]],dtype=int64)>