PyTorch-实现对表格类型数据的一维卷积(CNN1D)

4 篇文章 0 订阅
3 篇文章 2 订阅

数据集:首先看一下我自己的表格类型的数据

看到大家都私信要代码,太多了发不过来,我把代码放到github上了:

github链接: https://github.com/JiaBinBin233/CNN1D
我的数据集是一个二分类的数据集,是一个12维的数据(第一列为标签列,其他的11列是属性列)
在这里插入图片描述

神经网络架构

#两层卷积层,后面接一个全连接层
class Learn(nn.Module):
    def __init__(self):
        super(Tudui, self).__init__()
        self.model1 = nn.Sequential(
        	#输入通道一定为1,输出通道为卷积核的个数,2为卷积核的大小(实际为一个[1,2]大小的卷积核)
            nn.Conv1d(1, 16, 2),  
            nn.Sigmoid(),
            nn.MaxPool1d(2),  # 输出大小:torch.Size([128, 16, 5])
            nn.Conv1d(16, 32, 2),
            nn.Sigmoid(),
            nn.MaxPool1d(4),  # 输出大小:torch.Size([128, 32, 1])
            nn.Flatten(),  # 输出大小:torch.Size([128, 32])
        )
        self.model2 = nn.Sequential(
            nn.Linear(in_features=32, out_features=2, bias=True),
            nn.Sigmoid(),
        )
    def forward(self, input):
        x = self.model1(input)
        x = self.model2(x)
        return x

我个人认为输入的数据是什么格式的是一个难点

首先看一下没有经过处理过的数据

for data in train_loader:
    X_data, Y_data = data[0], data[1]
    print(X_data)
    print(X_data.shape)
输出结果如下

在这里插入图片描述
原始数据是一个128行11列的数据,每一行数据代表一个样本,一共有128个样本(batch_size=128)

对数据进行处理,处理成可以输入到卷积网络的数据形式

X_data = X_data.reshape(-1,1,11) # -1表示让系统自己计算有多少个样本,这个操作的目的就是把数据转换为3维的
print(X_data)
print(X_data.shape)
输出结果如下

在这里插入图片描述

运行

output = Learn(X_data)
loss = loss_function(output, Y_data)
optim.zero_grad()
loss.backward()
optim.step()

原理

一维卷积的流程是卷积核对每一条样本进行横向卷积(卷积核的个数为输出通道的大小),对每条样本卷积的次数为卷积核的个数。每条样本被卷积具体的卷积流程我在别人的博客截了个图方便大家理解

在这里插入图片描述

这个图就是卷积核对一个样本进行卷积的具体操作

  • 57
    点赞
  • 323
    收藏
    觉得还不错? 一键收藏
  • 72
    评论
以下是一个简单的一维卷积CNN-LSTM PyTorch模型代码,用于预测刀具磨损量。这个模型由一维卷积层和LSTM层组成,用于处理时间序列数据。 ```python import torch import torch.nn as nn import torch.optim as optim import numpy as np class ConvLSTM(nn.Module): def __init__(self, input_size, hidden_size, kernel_size, num_layers, dropout): super(ConvLSTM, self).__init__() self.hidden_size = hidden_size self.num_layers = num_layers self.conv = nn.Conv1d(input_size, input_size, kernel_size, padding=(kernel_size - 1) // 2) self.lstm = nn.LSTM(input_size, hidden_size, num_layers, dropout=dropout, batch_first=True) self.linear = nn.Linear(hidden_size, 1) def forward(self, x): x = self.conv(x) h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) out, _ = self.lstm(x, (h0, c0)) out = self.linear(out[:, -1, :]) return out # Hyperparameters input_size = 1 hidden_size = 64 kernel_size = 3 num_layers = 2 dropout = 0.2 lr = 0.001 num_epochs = 100 # Model, Loss and Optimizer model = ConvLSTM(input_size, hidden_size, kernel_size, num_layers, dropout).to(device) criterion = nn.MSELoss() optimizer = optim.Adam(model.parameters(), lr=lr) # Train the model for epoch in range(num_epochs): for i, (inputs, labels) in enumerate(train_loader): inputs = inputs.to(device) labels = labels.to(device) # Forward pass outputs = model(inputs) loss = criterion(outputs, labels) # Backward and optimize optimizer.zero_grad() loss.backward() optimizer.step() # Print the loss if (epoch+1) % 10 == 0: print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item())) # Test the model with torch.no_grad(): correct = 0 total = 0 for inputs, labels in test_loader: inputs = inputs.to(device) labels = labels.to(device) # Forward pass outputs = model(inputs) # Calculate the loss loss = criterion(outputs, labels) total += labels.size(0) correct += (abs(outputs - labels) <= 0.1).sum().item() print('Test Accuracy of the model on the test data: {} %'.format(100 * correct / total)) ``` 在训练之前,你需要准备你的数据,并将其转换为PyTorch张量格式。你可以使用PyTorch的DataLoader类来批量加载数据。在上面的代码中,我们使用均方误差损失函数和Adam优化器来训练模型。最后,我们在测试集上评估了模型的准确性。
评论 72
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值