如何(有效地)在TensorFlow中应用通道方式的完全连接层

问题描述 投票:4回答:1

我再次向你伸手去抓我可以上班的东西,但真的很慢。我希望你能帮助我优化它。

我正在尝试在TensorFlow中实现一个卷积自动编码器,在编码器和解码器之间有一个很大的潜在空间。通常,人们会将编码器连接到具有完全连接层的解码器,但是因为这个潜在空间具有高维度,所以这样做会产生太多的特征,使其在计算上是可行的。

我在this paper找到了一个很好的解决这个问题的方法。他们将其称为“通道完全连接层”。它基本上是每个通道的完全连接层。

我正在努力实现,我让它工作,但图形的生成需要很长时间。到目前为止这是我的代码:

def _network(self, dataset, isTraining):
        encoded = self._encoder(dataset, isTraining)
        with tf.variable_scope("fully_connected_channel_wise"):
            shape = encoded.get_shape().as_list()
            print(shape)
            channel_wise = tf.TensorArray(dtype=tf.float32, size=(shape[-1]))
            for i in range(shape[-1]):  # last index in shape should be the output channels of the last conv
                channel_wise = channel_wise.write(i, self._linearLayer(encoded[:,:,i], shape[1], shape[1]*4, 
                                  name='Channel-wise' + str(i), isTraining=isTraining))
            channel_wise = channel_wise.concat()
            reshape = tf.reshape(channel_wise, [shape[0], shape[1]*4, shape[-1]])
        reconstructed = self._decoder(reshape, isTraining)
        return reconstructed

那么,任何想法为什么这么长时间?实际上这是一个范围(2048),但所有的线性层都非常小(4x16)。我是以错误的方式接近这个吗?

谢谢!

python tensorflow deep-learning autoencoder
1个回答
2
投票

您可以在Tensorflow中检查它们的实现。这是他们实现的“通道完全连接层”。

def channel_wise_fc_layer(self, input, name): # bottom: (7x7x512)
    _, width, height, n_feat_map = input.get_shape().as_list()
    input_reshape = tf.reshape( input, [-1, width*height, n_feat_map] )
    input_transpose = tf.transpose( input_reshape, [2,0,1] )

    with tf.variable_scope(name):
        W = tf.get_variable(
                "W",
                shape=[n_feat_map,width*height, width*height], # (512,49,49)
                initializer=tf.random_normal_initializer(0., 0.005))
        output = tf.batch_matmul(input_transpose, W)

    output_transpose = tf.transpose(output, [1,2,0])
    output_reshape = tf.reshape( output_transpose, [-1, height, width, n_feat_map] )

    return output_reshape

https://github.com/jazzsaxmafia/Inpainting/blob/8c7735ec85393e0a1d40f05c11fa1686f9bd530f/src/model.py#L60

主要思想是使用tf.batch_matmul函数。

但是,在最新版本的Tensorflow中删除了tf.batch_matmul,您可以使用tf.matmul来替换它。

© www.soinside.com 2019 - 2024. All rights reserved.