-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.py
68 lines (59 loc) · 2.62 KB
/
test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import os
import torch
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import time
import psutil
# 数据集放置路径
data_save_pth = "./data"
# 数据转换
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
# 使用官方方式加载数据集
trainset = torchvision.datasets.CIFAR10(root=data_save_pth, train=True, download=True, transform=transform)
trainloader = DataLoader(trainset, batch_size=32, shuffle=True, num_workers=4)
testset = torchvision.datasets.CIFAR10(root=data_save_pth, train=False, download=True, transform=transform)
testloader = DataLoader(testset, batch_size=32, shuffle=False, num_workers=4)
# 检查数据集大小
print(f'Training set size: {len(trainset)}')
print(f'Test set size: {len(testset)}')
# 定义CNN模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# 第一个卷积层,输入通道3(RGB图像),输出通道32,卷积核大小3x3
self.conv1 = nn.Conv2d(3, 32, 3, stride=1, padding=1)
# 池化层,窗口大小2x2,步长2
self.pool = nn.MaxPool2d(2, 2)
# 第二个卷积层,输入通道32,输出通道64,卷积核大小3x3
self.conv2 = nn.Conv2d(32, 64, 3, stride=1, padding=1)
# 第一个全连接层,输入特征数为64*8*8(因为经过两次池化后,特征图大小减半两次),输出特征数256
self.fc1 = nn.Linear(64 * 8 * 8, 256)
# 第二个全连接层,输入特征数256,输出特征数10(CIFAR-10数据集的类别数)
self.fc2 = nn.Linear(256, 10)
def forward(self, x):
# 应用第一个卷积层和激活函数ReLU
x = self.pool(F.relu(self.conv1(x)))
# 应用第二个卷积层和激活函数ReLU
x = self.pool(F.relu(self.conv2(x)))
# 展平特征图,为全连接层准备
x = x.view(-1, 64 * 8 * 8)
# 应用第一个全连接层和激活函数ReLU
x = F.relu(self.fc1(x))
# 应用第二个全连接层
x = self.fc2(x)
return x
# 初始化网络和优化器
net = Net()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
criterion = nn.CrossEntropyLoss()
# 将模型移动到GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
net.to(device)
criterion.to(device)