【问题标题】:Tensorflow, how to implement sorting layerTensorflow,如何实现排序层
【发布时间】:2020-10-18 16:54:18
【问题描述】:

我正在尝试在 keras 中有一个层,它采用平面张量 x(其中没有零值并且形状 =(batch_size,单位))乘以 mask(形状相同),并且它将以屏蔽值首先放置在输出中的方式对其进行排序(元素值的顺序无关紧要)。为了清楚起见,这里是一个示例(batch_size = 1,units = 8):

看起来很简单,但问题是我找不到好的解决方案。任何代码或想法表示赞赏。

【问题讨论】:

    标签: tensorflow keras deep-learning neural-network keras-layer


    【解决方案1】:

    我目前的代码如下,如果您知道更有效的方法,请告诉我。

    class Sort(keras.layers.Layer):
      
      def call(self, inputs):
        x = inputs.numpy()
        nonx, nony = x.nonzero()    # idxs of nonzero elements
        zero = [np.where(x == 0)[0][0], np.where(x == 0)[1][0]]   # idx of first zero
        x_shape = tf.shape(inputs)
        result = np.zeros((x_shape[0], x_shape[1], 2), dtype = 'int')   # mapping matrix
    
        result[:, :, 0] += zero[0]
        result[:, :, 1] += zero[1]
        p = np.zeros((x_shape[0]), dtype = 'int')
        for i, j in zip(nonx, nony):
          result[i, p[i]] = [i, j]
          p[i] += 1
    
        y = tf.gather_nd(inputs, result)
        return y
    

    【讨论】:

      猜你喜欢
      • 2017-12-17
      • 1970-01-01
      • 2017-04-18
      • 2018-02-11
      • 2017-08-02
      • 2021-12-18
      • 2020-10-16
      • 2019-09-20
      • 1970-01-01
      相关资源
      最近更新 更多