【问题标题】:How to (efficiently) apply a channel-wise fully connected layer in TensorFlow如何(有效地)在 TensorFlow 中应用通道级全连接层
【发布时间】:2018-05-13 08:26:53
【问题描述】:

我又来找你了,我可以开始工作,但真的很慢。希望大家帮我优化一下。

我正在尝试在 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】:

    您可以在 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 函数。

    不过,tf.batch_matmul 在最新版本的 Tensorflow 中被移除了,您可以使用 tf.matmul 来替换它。

    【讨论】:

    • 哇!谢谢!我不敢相信他们在网上有一个实施,甚至没有在文字上提到它!另外,这和我做的相差甚远,不知道他们是不是和我有同样的问题。
    猜你喜欢
    • 1970-01-01
    • 2018-12-13
    • 2017-12-14
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 2023-03-03
    相关资源
    最近更新 更多