import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torchvision import matplotlib.pyplot as plt import numpy as np device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() self.conv1 = nn.Sequential( nn.Conv2d(1, 16, 5, 1, 2), nn.ReLU(), nn.MaxPool2d(2) ) self.conv2 = nn.Sequential( nn.Conv2d(16, 32, 5, 1, 2), nn.ReLU(), nn.MaxPool2d(2) ) self.conv3 = nn.Sequential( nn.Conv2d(32, 64, 5, 1, 2), nn.ReLU(), nn.MaxPool2d(2) ) self.conv4 = nn.Sequential( nn.Conv2d(64, 32, 5, 1, 2), nn.ReLU(), nn.MaxPool2d(2) ) self.out = nn.Linear(32, 10) # 确保输出类别数正确 def forward(self, x): x = self.conv1(x).to(device) # 将数据迁移到GPU x = self.conv2(x).to(device) x=self.conv3(x).to(device) x = self.conv4(x).to(device) x = x.view(x.size(0), -1).to(device) x = self.out(x).to(device) return x