32 lines
1.2 KiB
Python
32 lines
1.2 KiB
Python
import torch
|
|
import torch.nn as nn
|
|
import torch.optim as optim
|
|
|
|
class Simple1DCNN(nn.Module):
|
|
def __init__(self, input_size, num_classes):
|
|
super(Simple1DCNN, self).__init__()
|
|
self.conv1 = nn.Conv1d(in_channels=1, out_channels=32, kernel_size=3, stride=1, padding=1)
|
|
self.relu = nn.ReLU()
|
|
self.pool = nn.MaxPool1d(kernel_size=2, stride=2)
|
|
self.conv2 = nn.Conv1d(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1)
|
|
self.fc1 = nn.Linear(64 * (input_size // 4), 128) # 假设经过两次池化后,长度减半两次
|
|
self.fc2 = nn.Linear(128, num_classes)
|
|
|
|
def forward(self, x):
|
|
x = self.pool(self.relu(self.conv1(x)))
|
|
x = self.pool(self.relu(self.conv2(x)))
|
|
x = x.view(-1, 64 * (self.input_size // 4)) # 展平特征图
|
|
x = self.relu(self.fc1(x))
|
|
x = self.fc2(x)
|
|
return x
|
|
|
|
# 实例化模型
|
|
input_size = 100 # 假设n=100
|
|
num_classes = 10 # 假设有10个类别
|
|
model = Simple1DCNN(input_size, num_classes)
|
|
|
|
# 定义损失函数和优化器
|
|
criterion = nn.CrossEntropyLoss()
|
|
optimizer = optim.Adam(model.parameters(), lr=0.001)
|
|
|
|
# 训练和评估模型的代码与之前类似,这里不再赘述。 |