基于pytorch分别搭建一个一维卷积神经网络和二维卷积神经网络的代码
时间: 2024-04-19 07:21:30 浏览: 165
当使用PyTorch构建一维卷积神经网络(1D CNN)和二维卷积神经网络(2D CNN)时,需要使用PyTorch的`nn`模块来定义网络结构。下面是分别搭建一维卷积神经网络和二维卷积神经网络的代码示例:
一维卷积神经网络(1D CNN)的代码示例:
```python
import torch
import torch.nn as nn
class OneDCNN(nn.Module):
def __init__(self, input_size, num_classes):
super(OneDCNN, self).__init__()
self.conv1 = nn.Conv1d(in_channels=input_size, out_channels=16, kernel_size=3)
self.relu = nn.ReLU()
self.fc = nn.Linear(16, num_classes)
def forward(self, x):
x = self.conv1(x)
x = self.relu(x)
x = torch.mean(x, dim=2) # 对最后一个维度求平均值
x = self.fc(x)
return x
# 创建一个输入样本
input_size = 10 # 输入特征的维度
num_classes = 2 # 分类的类别数
input_sample = torch.randn(1, input_size, 100) # 输入样本的形状为(batch_size, input_size, sequence_length)
# 创建一个1D CNN模型实例
model = OneDCNN(input_size, num_classes)
# 前向传播
output = model(input_sample)
print(output)
```
二维卷积神经网络(2D CNN)的代码示例:
```python
import torch
import torch.nn as nn
class TwoDCNN(nn.Module):
def __init__(self, num_classes):
super(TwoDCNN, self).__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3)
self.relu = nn.ReLU()
self.pool = nn.MaxPool2d(kernel_size=2)
self.fc = nn.Linear(16 * 13 * 13, num_classes)
def forward(self, x):
x = self.conv1(x)
x = self.relu(x)
x = self.pool(x)
x = x.view(x.size(0), -1) # 将特征展平
x = self.fc(x)
return x
# 创建一个输入样本
num_classes = 10 # 分类的类别数
input_sample = torch.randn(1, 3, 32, 32) # 输入样本的形状为(batch_size, channels, height, width)
# 创建一个2D CNN模型实例
model = TwoDCNN(num_classes)
# 前向传播
output = model(input_sample)
print(output)
```
阅读全文