PyTorch使用一维卷积对时间序列数据分类

数据展示

时间序列数据也就是自变量是时间的一维数据,平时接触到的y= x, y = sinx等都是可以认为是时间序列数据。本次实验使用的是波形数据,可以认为不同形态的反射波形代表不同的类别。以下分别是两种类别的数据集,和四种类别的数据集,同一种颜色代表同一种类别。

在这里插入图片描述

在这里插入图片描述

模型搭建

采用PyTorch搭建网络模型,两层卷积层,卷积核大小为64,32。模型结构如下

在这里插入图片描述

由于pytorch的网络模型画网络结构不像tensorflow那么方便,需要转化为onnx模型,在用netron画出来,参考后面的源码。

源码

网络模型

import torch
import torch.nn as nn
from torch.utils.data import Dataset

class CNNnet(nn.Module):
    def __init__(self, *, inputLength = 80, kernelSize = 3, kindsOutput = 4):
        super().__init__()
        filterNum1 = 64
        filterNum2 = 32 
        self.layer1 = nn.Sequential(
            nn.Conv1d(1, filterNum1, kernelSize), # inputLength - kernelSize + 1 = 80 - 3 + 1 = 78
            nn.BatchNorm1d(filterNum1),
            nn.ReLU(inplace=True),
            nn.MaxPool1d(kernelSize, stride = 1) # 78 - 3 + 1 = 76
        )
        self.layer2 = nn.Sequential(
            nn.Conv1d(filterNum1, filterNum2, kernelSize), # 76 - 3 + 1 = 74
            nn.BatchNorm1d(filterNum2),
            nn.ReLU(inplace=True),
            nn.MaxPool1d(kernelSize, stride = 1) # 74 - 3 + 1 = 72
        )
        self.dropout = nn.Dropout(0.2)
        self.fc = nn.Linear(filterNum2 * (inputLength - 8), kindsOutput)
    
    def forward(self,x):
        x = x.to(torch.float32)
        x = self.layer1(x)
        x = self.layer2(x)
        x = x.view(x.size(0), -1)
        x = self.fc(x)
        x = self.dropout(x)
        return x
    
 class DatasetOfDiv(Dataset):
    def __init__(self, data_features, data_target):
        self.len = len(data_features)
        self.features = torch.from_numpy(data_features)
        self.target = torch.from_numpy(data_target)

    def __getitem__(self, index):
        return self.features[index], self.target[index]

    def __len__(self):
        return self.len

请注意,这里的DatasetOfDiv是需要为自己的数据集,继承Dataset这个类来实现。

模型训练

def train(trainData, trainLabel, *, savePath='..\models\pytorch', modelName = 'model.pt', epochs = 100, batchSize = 4, classNum = 4):
    trainFeatures, trainTarget, testFeatures, testTarget = datasetSplit(trainData, trainLabel)
    print('trainFeatures shape:', trainFeatures.shape, '\ttestFeatures shape:', testFeatures.shape)
    trainSet = DatasetOfDiv(trainFeatures, trainTarget)
    trainLoader = DataLoader(dataset=trainSet, batch_size=batchSize, shuffle=True, drop_last=True)

    model = CNNnet(inputLength=trainFeatures.shape[1], kindsOutput = classNum)
    # criterion = nn.MSELoss()
    criterion = nn.CrossEntropyLoss()
    optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
    model.train()

    start_time = time.time()
    for epoch in range(epochs):
        for seq, y_train in trainLoader:
            # 每次更新参数前都梯度归零和初始化
            # sampleSize = seq.shape[0]
            optimizer.zero_grad()
            # 注意这里要对样本进行reshape,转换成conv1d的(batch size, channel, series length)
            # y_pred = model(seq.reshape(sampleSize, 1, -1))
            y_pred = model(seq.reshape(batchSize, 1, -1))
            y_train = y_train.long()
            loss = criterion(y_pred, y_train)
            loss.backward()
            optimizer.step()
        # compute test accuracy
        _y_pred = model(torch.from_numpy(testFeatures).reshape(testFeatures.shape[0], 1, -1)) 
        y_pred = torch.max(_y_pred, 1)[1]
        numCorrect = (y_pred.data.numpy() == testTarget).astype(int).sum()
        numOfTestSample = testTarget.size
        accuracy = float(numCorrect)/numOfTestSample
        print(f'Epoch: \t{epoch+1} \t Accuracy: {accuracy:.2f} \t Loss: {loss.item():.5f} \
                \t NumOfTestSample:{numOfTestSample} \t numOfPredictCorrect:{numCorrect}'.replace(" ",""))
    print(f'\nDuration: {time.time() - start_time:.0f} seconds')
    # torch.save(model.state_dict(), savePath + '\\' + modelName)
    # torch.save(model, savePath + '\\' + modelName)
    torch.onnx.export(
        model,
        torch.randn(5, 1, trainFeatures.shape[1]),
        savePath + '\\' + 'model.onnx',
        export_params=True,
        # opset_version=8,
    )
    return model

模型测试

def testModelEval(self, modelPath, trainData, trainLabel, *, classNum = 4):
    model = CNNnet(inputLength = trainData.shape[1], kindsOutput = classNum)
    model.load_state_dict(torch.load(modelPath))
    model.eval()

    testData = trainData
    _eval_result = model(torch.from_numpy(testData).reshape(testData.shape[0], 1, -1))
    eval_result = torch.max(_eval_result, 1)[1]
    result = eval_result.data.numpy()

    predErrNum =  result.size - result[trainLabel==result].size
    print('sum:', result.size, '\tpredErrNum:', predErrNum)

使用演示

def main():
    filePath = '\your\data\path'
    trainData, trainLabel = getYourData(filePath) #getYourData是你自己的数据解析函数
    train(trainData,trainLabel)
    ...

if __name__ == '__main__':
    main()

enjoy~

有疑问评论区交流

参考文档

[深度应用]·使用一维卷积神经网络处理时间序列数据
CNN实现时间序列预测(PyTorch版)
积神经网络处理时间序列数据
PyTorch搭建CNN实现时间序列预测(风速预测)

  • 5
    点赞
  • 80
    收藏
    觉得还不错? 一键收藏
  • 27
    评论
图卷积网络(Graph Convolutional Network,GCN)是一种用于图结构的深度学习模型,可以用于节点分类、图分类和链接预测等任务。它扩展了传统的卷积神经网络(Convolutional Neural Network,CNN)和递归神经网络(Recurrent Neural Network,RNN)等模型,以适应处理图结构的数据。 时序预测是指基于时间序列数据进行未来数值或趋势预测的任务。在pytorch框架中,可以利用图卷积网络进行时序预测。一种常见的应用场景是利用图结构表示多个时间序列,其中节点表示不同的时间点,边表示节点之间的依赖关系。通过在图卷积网络中使用时间信息和节点特征,可以学习到时间序列数据之间的时序依赖关系,从而实现对未来数值或趋势的预测。 具体实现时,可以使用pytorch中的torch_geometric库来构建图卷积网络。首先,需要准备好时间序列数据和对应的图结构。然后,可以定义一个图卷积网络模型,该模型可以包括多个图卷积层和激活函数。在每个时间节点上,可以通过前向传播的方式将当前节点的特征与其邻居节点的特征进行聚合,并经过激活函数得到新的节点特征表示。最后,可以通过输出层将节点的特征映射到预测结果的维度上。 训练时,可以使用已有的时间序列数据进行监督学习,通过最小化损失函数来更新模型的参数。在预测时,可以将新的时间序列数据输入到已经训练好的模型中,得到对未来数值或趋势的预测结果。 总而言之,图卷积网络在时序预测中的应用可以通过学习时间序列数据的时序依赖关系来实现对未来数值或趋势的预测,而在pytorch使用torch_geometric库可以方便地构建和训练图卷积网络模型。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 27
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值