用pytorch写一个一维卷积分类代码
时间: 2024-01-26 15:04:52 浏览: 74
torch实现自编码器-Pytorch卷积自动编码器
好的,下面是一个简单的一维卷积分类代码:
```python
import torch
import torch.nn as nn
# 定义模型
class Conv1DModel(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim):
super(Conv1DModel, self).__init__()
self.conv1 = nn.Conv1d(in_channels=input_dim, out_channels=hidden_dim, kernel_size=3, padding=1)
self.relu1 = nn.ReLU()
self.pool1 = nn.MaxPool1d(kernel_size=2)
self.conv2 = nn.Conv1d(in_channels=hidden_dim, out_channels=hidden_dim, kernel_size=3, padding=1)
self.relu2 = nn.ReLU()
self.pool2 = nn.MaxPool1d(kernel_size=2)
self.fc = nn.Linear(hidden_dim * 8, output_dim)
def forward(self, x):
x = self.conv1(x)
x = self.relu1(x)
x = self.pool1(x)
x = self.conv2(x)
x = self.relu2(x)
x = self.pool2(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
# 定义数据集
input_dim = 10 # 输入维度
output_dim = 2 # 输出维度
num_samples = 1000 # 样本数
seq_len = 20 # 序列长度
X = torch.randn(num_samples, input_dim, seq_len)
y = torch.randint(0, output_dim, (num_samples,))
# 定义超参数
learning_rate = 0.001
num_epochs = 10
batch_size = 32
# 定义模型、损失函数和优化器
model = Conv1DModel(input_dim, 16, output_dim)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# 训练模型
for epoch in range(num_epochs):
for i in range(0, num_samples, batch_size):
batch_X = X[i:i+batch_size]
batch_y = y[i:i+batch_size]
optimizer.zero_grad()
outputs = model(batch_X)
loss = criterion(outputs, batch_y)
loss.backward()
optimizer.step()
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))
# 测试模型
with torch.no_grad():
outputs = model(X)
_, predicted = torch.max(outputs.data, 1)
correct = (predicted == y).sum().item()
total = y.size(0)
print('Accuracy: {:.2f}%'.format(100 * correct / total))
```
这个模型包括两个卷积层和一个全连接层,用于对一维数据进行分类。你可以根据具体的需求来修改模型的结构和超参数。
阅读全文