关于CIFAR-10数据集,可以访问它的官网进行下载:
http://www.cs.toronto.edu/~kriz/cifar.html。
CIFAR包含常见的10类物体的照片,照片的size 为32×32,每一类照片有6000张,所以一共6000万张照片,我们把6万张照片随机选出5万张照片作为training,剩余的1万张作为test.
import torch
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision import transforms
def main():
batchsz = 32
#当前目录下新建文件夹'cifar',train = True,transform对数据进行变换,download=True自动下载数据集
cifar_train = datasets.CIFAR10('cifar', True, transform=transforms.Compose([
transforms.Resize((32, 32)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
]), download=True)
#DataLoader方便一次加载多个,第一个参数为数据集cifar_train,第二个参数batch_size为每次批处理数量,
#根据显卡设置batch_size,不要太小。第三个参数shuffle为打乱,设置成True。
cifar_train = DataLoader(cifar_train, batch_size=batchsz, shuffle=True)
cifar_test = datasets.CIFAR10('cifar', False, transform=transforms.Compose([
transforms.Resize((32, 32)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
]), download=True)
cifar_test = DataLoader(cifar_test, batch_size=batchsz, shuffle=True)
#通过iter方法把DataLoader迭代器先得到,使用迭代器.next()方法得到一个batch。
x, label = iter(cifar_train).next()
print('x:', x.shape, 'label:', label.shape)
if __name__ == '__main__':
main()
import torch
from torch import nn
from torch.nn import functional as F
class Lenet5(nn.Module):
"""
for cifar10 dataset.
"""
def __init__(self):
super(Lenet5, self).__init__()
self.conv_unit = nn.Sequential(
# x: [b, 3, 32, 32] => [b, 6, ]
#第一个参数为输入的channel,第二个参数为输出的channel,...
nn.Conv2d(3, 6, kernel_size=5, stride=1, padding=0),
nn.MaxPool2d(kernel_size=2, stride=2, padding=0),
#
nn.Conv2d(6, 16, kernel_size=5, stride=1, padding=0),
nn.MaxPool2d(kernel_size=2, stride=2, padding=0),
#
)
# flatten
# fc unit
self.fc_unit = nn.Sequential(
nn.Linear(16*5*5, 120),
nn.ReLU(),
nn.Linear(120, 84),
nn.ReLU(),
nn.Linear(84, 10)
)
# [b, 3, 32, 32]
tmp = torch.randn(2, 3, 32, 32)
out = self.conv_unit(tmp)
# [b, 16, 5, 5]
print('conv out:', out.shape)
# # use Cross Entropy Loss
#self.criteon = nn.CrossEntropyLoss()
def forward(self, x):
"""
:param x: [b, 3, 32, 32]
:return:
"""
batchsz = x.size(0)
# [b, 3, 32, 32] => [b, 16, 5, 5]
x = self.conv_unit(x)
# [b, 16, 5, 5] => [b, 16*5*5]
x = x.view(batchsz, 16*5*5) #16*5*5也可写成-1
# [b, 16*5*5] => [b, 10]
logits = self.fc_unit(x)
# # [b, 10]
#pred = F.softmax(logits, dim=1)
#nn.CrossEntropyLoss()包含softmax操作,所以不需要再写
#loss = self.criteon(logits, y)
return logits
def main():
net = Lenet5()
tmp = torch.randn(2, 3, 32, 32)
out = net(tmp)
print('lenet out:', out.shape)
if __name__ == '__main__':
main()
device = torch.device('cuda')
model = Lenet5().to(device)
criteon = nn.CrossEntropyLoss().to(device)
optimizer = optim.Adam(model.parameters(), lr=1e-3)
print(model)
for epoch in range(1): #1改为1000
model.train()
for batchidx, (x, label) in enumerate(cifar_train):
# 这里是对一个batch迭代一次,一次batch 32张图片
# [b, 3, 32, 32], [b]
x, label = x.to(device), label.to(device)
logits = model(x)
# logits: [b, 10], label: [b], loss: tensor scalar
loss = criteon(logits, label)
# backprop
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 使用 .item()将最后一个标量loss转换成Numpy打印出来
print(epoch, 'loss:', loss.item())
model.eval()
with torch.no_grad():
# test
total_correct = 0
total_num = 0
for x, label in cifar_test:
# [b, 3, 32, 32], [b]
x, label = x.to(device), label.to(device)
# [b, 10]
logits = model(x)
# [b]
pred = logits.argmax(dim=1)
# [b] vs [b] => scalar tensor
correct = torch.eq(pred, label).float().sum().item()
total_correct += correct
total_num += x.size(0)
# print(correct)
acc = total_correct / total_num
print(epoch, 'test acc:', acc)
import torch
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision import transforms
from torch import nn, optim
from lenet5 import Lenet5
def main():
batchsz = 32
#当前目录下新建文件夹'cifar',train = True,transform对数据进行变换,download=True自动下载数据集
cifar_train = datasets.CIFAR10('cifar', True, transform=transforms.Compose([
transforms.Resize((32, 32)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
]), download=True)
#DataLoader方便一次加载多个,第一个参数为数据集cifar_train,第二个参数batch_size为每次批处理数量,
#根据显卡设置,不要太小。第三个参数shuffle为打乱,设置成True。
cifar_train = DataLoader(cifar_train, batch_size=batchsz, shuffle=True)
cifar_test = datasets.CIFAR10('cifar', False, transform=transforms.Compose([
transforms.Resize((32, 32)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
]), download=True)
cifar_test = DataLoader(cifar_test, batch_size=batchsz, shuffle=True)
#通过iter方法把DataLoader迭代器先得到,使用迭代器.next()方法得到一个batch。
x, label = iter(cifar_train).next()
print('x:', x.shape, 'label:', label.shape)
device = torch.device('cuda')
model = Lenet5().to(device)
criteon = nn.CrossEntropyLoss().to(device)
optimizer = optim.Adam(model.parameters(), lr=1e-3)
print(model)
for epoch in range(1000):
model.train()
for batchidx, (x, label) in enumerate(cifar_train):
# 这里是对一个batch迭代一次,一次batch 32张图片
# [b, 3, 32, 32], [b]
x, label = x.to(device), label.to(device)
logits = model(x)
# logits: [b, 10], label: [b], loss: tensor scalar
loss = criteon(logits, label)
# backprop
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 使用 .item()将最后一个标量loss转换成Numpy打印出来
print(epoch, 'loss:', loss.item())
model.eval()
with torch.no_grad():
# test
total_correct = 0
total_num = 0
for x, label in cifar_test:
# [b, 3, 32, 32], [b]
x, label = x.to(device), label.to(device)
# [b, 10]
logits = model(x)
# [b]
pred = logits.argmax(dim=1)
# [b] vs [b] => scalar tensor
correct = torch.eq(pred, label).float().sum().item()
total_correct += correct
total_num += x.size(0)
# print(correct)
acc = total_correct / total_num
print(epoch, 'test acc:', acc)
if __name__ == '__main__':
main()