0


卷积自编码器中注意机制和使用线性模型进行超参数分析

新神经网络架构设计的最新进展之一是注意力模块的引入。首次出现在在NLP 上的注意力背后的主要思想是为数据的重要部分添加权重。在卷积神经网络的情况下,第一个注意机制是在卷积块注意模型中提出的。其中注意机制分为两个部分:通道注意模块和空间注意模块。

空间注意模块通过将图像分解为两个通道,即最大池化和跨通道的平均池化来创建特征空间的掩码。这一层是卷积层的输入,卷积层只应用一个保持与输入相同大小的滤波器。然后使用sigmoid激活创建从0到1的激活映射。生成的新的映射会按比例缩放输入,它通过缩放输入增强空间特征。

  1. class SpatialAttention(Layer):
  2. '''
  3. Custom Spatial attention layer
  4. '''
  5. def __init__(self, **kwargs):
  6. super(SpatialAttention, self).__init__()
  7. self.kwargs = kwargs
  8. def build(self, input_shapes):
  9. self.conv = Conv2D(filters=1, kernel_size=5, strides=1, padding='same')
  10. def call(self, inputs):
  11. pooled_channels = tf.concat(
  12. [tf.math.reduce_max(inputs, axis=3, keepdims=True),
  13. tf.math.reduce_mean(inputs, axis=3, keepdims=True)],
  14. axis=3)
  15. scale = self.conv(pooled_channels)
  16. scale = tf.math.sigmoid(scale)
  17. return inputs * scale

我们可以将其添加到密集卷积块中,创建自编码器模型。还可以通过添加一个选项来检查注意力模块的是否存在

  1. def MakeConvolutionBlock(X, Convolutions,BatchNorm=True,Drop=True,SpAttention=True,Act='relu'):
  2. '''
  3. Parameters
  4. ----------
  5. X : keras functional layer
  6. Previous layer in the model.
  7. Convolutions : int
  8. Number of convolutional filters.
  9. BatchNorm : bool, optional
  10. If True a batchnorm layer is added to the convolutional block.
  11. The default is True.
  12. Drop : bool, optional
  13. If true a Droput layer is added to the model. The default is True.
  14. SpAttention : bool, optional
  15. If true a SpatialAttention layer is added to the model. The default is True.
  16. Act : string, optional
  17. Controls the kind of activation to be used. The default is 'relu'.
  18. Returns
  19. -------
  20. X : keras functiona layer
  21. Block of layers added to the model.
  22. '''
  23. X = Conv2D(Convolutions, (3,3), padding='same',use_bias=False)(X)
  24. if SpAttention:
  25. X = SpatialAttention()(X)
  26. if BatchNorm:
  27. X = BatchNormalization()(X)
  28. if Drop:
  29. X = Dropout(0.2)(X)
  30. X=Activation(Act)(X)
  31. return X

随着函数中不同参数的数量增加,直接其添加到下一个函数会有问题。所以可以在 python 中使用 **kwargs 功能,它通过使用字典将关键字参数解包到一个函数中。只需将 **kwargs 添加到使用与主构建块相同的参数的函数中。

  1. def MakeDenseConvolutionalCoder(InputShape,Units,BlockDepth,UpSampling=False,**kwargs):
  2. '''
  3. Parameters
  4. ----------
  5. InputShape : tuple
  6. Input shape of the images.
  7. Units : Array-like
  8. Number of convolutional filters to apply per block.
  9. BlockDepth : int
  10. Size of the concatenated convolutional block.
  11. UpSampling : bool, optional
  12. Controls the upsamplig or downsampling behaviour of the network.
  13. The default is False.
  14. **kwargs
  15. keyword arguments from MakeConvolutionBlock.
  16. Returns
  17. -------
  18. InputFunction : Keras functional model input
  19. input of the network.
  20. localCoder : Keras functional model
  21. Coder model, main body of the autoencoder.
  22. '''
  23. if UpSampling:
  24. denseUnits=Units[::-1]
  25. Name="Decoder"
  26. else:
  27. denseUnits=Units
  28. Name="Encoder"
  29. nUnits = len(denseUnits)
  30. InputFunction=Input(shape=InputShape)
  31. X = Conv2D(denseUnits[0], (3, 3), padding='same',use_bias=False)(InputFunction)
  32. X=Activation('relu')(X)
  33. for k in range(1,nUnits-1):
  34. X=MakeDenseBlock(X,denseUnits[k],BlockDepth,**kwargs)
  35. if UpSampling:
  36. X=Conv2DTranspose(denseUnits[k], (3, 3), padding='same',use_bias=False,strides=(2,2))(X)
  37. else:
  38. X=Conv2D(denseUnits[k], (3, 3), padding='same',use_bias=False,strides=(2,2))(X)
  39. if UpSampling:
  40. X=Conv2D(1, (3, 3), padding='same',use_bias=False)(X)
  41. X=BatchNormalization()(X)
  42. Output=Activation('sigmoid')(X)
  43. else:
  44. X=Conv2D(denseUnits[-1], (3, 3), padding='same',use_bias=False)(X)
  45. X=BatchNormalization()(X)
  46. Output=Activation('relu')(X)
  47. localCoder=Model(inputs=InputFunction,outputs=Output,name=Name)
  48. return InputFunction,localCoder

上面代码创建了自编码器的主体,并通过在其间添加采样层,我们就可以定义变分自编码器。使用 MNIST 数据集训练模型样本可以得到下面类似的结果。

已经定义了神经网络的架构,下面就是评估其他超参数。随着超参数数量的增加,搜索空间的复杂性也随之增加。如果没有明显的差异,许多不同类型的参数组合可能会使解释变得困难。为了规避所有这些问题的一种简单方法是将简单的线性模型应用于在不同设置下训练的模型的性能数据。

  1. names = ['BatchNorm','Dropout','SpatialAttention','Activation_elu','Activation_relu','Activation_selu','Activation_sigmoid']
  2. container = []
  3. for conf in configs:
  4. initial = [int(conf[ky]) for ky in ['BatchNorm', 'Drop', 'SpAttention']]
  5. for k,val in enumerate(activationNames):
  6. current=[0,0,0,0]
  7. if conf['Act']==val:
  8. current[k]=1
  9. break
  10. initial.extend(current)
  11. container.append(initial)
  12. linearModel = sm.OLS(performanceA,np.array(container))
  13. results = linearModel.fit()
  14. results.summary(xname=names)

从这个线性模型中,系数的解释非常简单。正系数表示性能值增加,而负值表示性能值降低。当使用重建损失时,负系数将表示性能提高。

从这个简单的线性模型中,可以看到选择添加到主构建块中的三种不同类型的层提高了模型的性能。在改变激活函数的同时,模型性能向相反的方向移动。即使适合线性模型的样本量很小,它也可以将优化工作导向特定方向。

本文的完整代码在这里:https://github.com/TavoGLC/DataAnalysisByExample/blob/master/NeuralNetworks/MNISTAttention.py

作者:Octavio Gonzalez-Lugo

“卷积自编码器中注意机制和使用线性模型进行超参数分析”的评论:

还没有评论