创建自定义层/函数以重新排列层值的正确方法(使用Tensorflow的Keras)

2024-10-06 12:04:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要重新排列一个张量值,然后在Keras中重新排列它,但是我正在努力用Tensorflow后端重新排列Keras中的张量。你知道吗

这个自定义层/函数将遍历这些值,然后通过一个跨距公式重新排列这些值 这似乎没有权重,所以我假设是无状态的,不会影响反向传播。你知道吗

但它需要列表切片:

out_array[b,channel_out, row_out, column_out] = in_array[b,i,j,k] 这只是我正在努力解决的问题之一。你知道吗

这是函数/层

def reorg(tensor, stride):

    batch,channel, height, width = (tensor.get_shape())
    out_channel = channel * (stride * stride)
    out_len = length//stride
    out_width = width//stride

    #create new empty tensor  
    out_array = K.zeros((batch, out_channel, out_len, out_width))

    for b in batch:    
        for i in range(channel):
            for j in range(height):
                for k in range(width):
                    channel_out = i + (j % stride) * (channel * stride) + (k % stride) * channel
                    row_out = j//stride
                    column_out = k//stride
                    out_array[b,channel_out, row_out, column_out] = K.slice(in_array,[b,i,j,k], size = (1,1,1,1))


    return out_array.astype("int")

我在Keras中创建自定义函数/层的经验不多, 所以不太确定我是否走对了方向。你知道吗

下面是代码位根据步幅所做的操作(这里是2):

enter image description here

https://towardsdatascience.com/training-object-detection-yolov2-from-scratch-using-cyclic-learning-rates-b3364f7e4755


Tags: 函数inforbatchchannelrangecolumnout
1条回答
网友
1楼 · 发布于 2024-10-06 12:04:18

当你说重新排列时,你的意思是改变你的轴的顺序吗?有一个名为tf.transpose的函数,可以在自定义层中使用。还有tf.keras.layers.Permute,可以在没有任何自定义代码的情况下使用它来对张量重新排序。你知道吗

如果您询问如何创建自定义层,则需要实现一些方法。文档在这里解释得很好:Custom Layers

from tensorflow.keras import layers
import tensorflow as tf

class Linear(layers.Layer):

  def __init__(self, units=32):
    super(Linear, self).__init__()
    self.units = units

  def build(self, input_shape):
    self.w = self.add_weight(shape=(input_shape[-1], self.units),
                             initializer='random_normal',
                             trainable=True)
    self.b = self.add_weight(shape=(self.units,),
                             initializer='random_normal',
                             trainable=True)

  def call(self, inputs):
    return tf.matmul(inputs, self.w) + self.b

相关问题 更多 >