在事件识别任务中,卷积神经网络(CNN)和gMLP(generalized Multilayer Perceptron)是两种常用的模型架构。CNN主要用于提取输入数据的局部特征,通过卷积和池化操作可以捕捉到数据的空间局部信息。而gMLP则是一种全连接的多层感知机模型,通过自注意力机制来建模序列数据的长距离依赖关系。

将CNN和gMLP结合起来可以充分利用它们各自的优势。在这个模型中,通过前两层的卷积层,CNN可以提取输入数据的空域特征。接着,将卷积层的输出通过gMLP模块处理,gMLP可以对序列数据进行建模,捕捉到时间序列中的长期依赖关系。最后,通过全连接层和softmax层将特征映射到标签空间,实现事件的分类。

相比于只使用CNN或只使用gMLP,将它们结合起来可以提高模型的性能。CNN可以提取输入数据的局部特征,而gMLP可以建模序列数据的长距离依赖关系,两者互补性较强。因此,通过将CNN和gMLP结合使用,可以更好地捕捉数据的空间和时间特征,提高事件识别的准确性。

模型代码:

import torch
import torch.nn as nn
import torch.nn.functional as F
from gmlp import SpatialGatingUnit ,gMLPBlock,gMLP

class CNN(nn.Module):
    def __init__(self):  # 初始化方法
        super(CNN, self).__init__()  # 初始化方法
        # 第一层卷积层,输入为 (1,10000,12)
        self.conv1 = nn.Sequential(  # input shape (1,10000,12)
            nn.Conv2d(  # 二维卷积层
                in_channels=1,  # input height   # 输入通道数
                out_channels=5,  # n_filters     # 输出通道数(卷积核数量)
                kernel_size=(200, 3),  # filter size  # 卷积核大小
                stride=(50, 1),  # filter movement/step   # 卷积核移动步长
                padding=1,  # 填充大小
            ),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, padding=1),  # 最大池化层
        )
        # 第二层卷积层,输入为 (5,99,7)
        self.conv2 = nn.Sequential(  # input shape (5,99,7)
            nn.Conv2d(5, 10, (20, 2), (4, 1), 1),  # output shape   # 输出通道数为10,卷积核大小为(20,2),步长为(4,1),填充为1
            nn.ReLU(),  # activation
            nn.MaxPool2d(kernel_size=2),  # 最大池化层  # output shape (10,10,4)
        )

        self.gmlp = gMLP(d_model=10, d_ffn=20, seq_len=40, num_layers=6)
              #  gmlp(data).shape

        self.flatten = nn.Flatten()

        self.linear = nn.Linear(in_features=400, out_features=64)
        self.relu = nn.ReLU(inplace=True)
        self.dropout = nn.Dropout(p=0.4)
        self.out = nn.Linear(64, 6)  # 全连接层,输出6个类别

    # 定义一个名为CNN的类,继承自PyTorch的nn.Module

    def forward(self, x):  # 前向传播方法
        x = self.conv1(x)  # 通过第一个卷积层序列
        x = self.conv2(x)  # 通过第二个卷积层序列
        # x = x.view(x.size(0), -1)      # 将张量展平
        # 四维转三维
        N, C, H, W = x.shape
        x = x.view(N, C, H * W).permute(0, 2, 1)
        x = self.gmlp(x)
        print(x.shape)
        x = self.flatten(x)#换顺序了 先展平 在输入线性层中
        x = self.linear(x)
        feature = x  # 提取特征
        x = self.relu(x)
        x = self.dropout(x)
        output = self.out(x)  # 通过全连接层得到输出
        return feature, output  # 返回特征和输出

数据说明:

我的数据包含六种类型的事件,总共有15,612个样本。训练数据和测试数据以8:2的比例从数据集中随机抽取,两者之间不存在重叠。每个样本数据是在时域上由10000个点组成和在空域上由12个相邻的空间点组成。


原文地址: https://www.cveoy.top/t/topic/cA4B 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录