- 环境:python3、torch1.2.0(torch1.5.0也可以)、torchvision0.4.0
- 代码:(注:DOWNLOAD_MNIST = False第一次应该设为True,原因在代码注释里)
import torch
from torch.autograd import Variable
import torch.utils.data as Data
import torchvision
import torch.nn as nn
import matplotlib.pyplot as plt
LR = 0.001
BATCH_SIZE = 50
EPOCH = 1
DOWNLOAD_MNIST = False
train_data = torchvision.datasets.MNIST(root='./mnist',
train=True,
transform=torchvision.transforms.ToTensor(),
download=DOWNLOAD_MNIST)
print(train_data.data.size())
print(train_data.targets.size())
plt.imshow(train_data.data[0].numpy(), cmap='gray')
plt.title('%i' % train_data.targets[0])
plt.show()
train_loader = Data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE,
shuffle=True, num_workers=2)
test_data = torchvision.datasets.MNIST(root='./mnist', train=False)
'''#测试集shape from (2000, 28, 28) to (2000, 1, 28, 28), value in range(0,1)
test_x = torch.unsqueeze(test_data.data, dim=[:2000].type(torch.FloatTensor).cuda()/255.
'''
with torch.no_grad():
test_x = Variable(torch.unsqueeze(test_data.data, dim=1)).type(torch.FloatTensor)[:2000]/255.
test_y = test_data.targets[:2000]
if __name__ == '__main__':
class CNN(torch.nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = torch.nn.Sequential(
nn.Conv2d(in_channels=1,
out_channels=16,
kernel_size=5,
stride=1,
padding=2,
),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2),
)
self.conv2 = nn.Sequential(
nn.Conv2d(16, 32, 5, 1, 2),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2)
)
self.out = nn.Linear(32*7*7, 10)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = x.view(x.size(0), -1)
output = self.out(x)
return output
cnn = CNN()
print(cnn)
optimizer = torch.optim.Adam(cnn.parameters(), lr=LR, betas=(0.9, 0.99))
loss_func = nn.CrossEntropyLoss()
for epoch in range(EPOCH):
for step, (b_x, b_y) in enumerate(train_loader):
output = cnn(b_x)
loss = loss_func(output, b_y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if step % 50 == 0:
test_output = cnn(test_x)
test_pred = torch.max(test_output, 1)[1].data
test_accuracy = float((test_pred == test_y).sum().item()) / float(test_y.size(0))
print('Epoch:', epoch, 'Train loss:', loss.data.cpu().numpy(), 'Test Accuracy:', test_accuracy)
test_output = cnn(test_x[:20])
pred_y = torch.max(test_output, 1)[1].data
print(pred_y.cpu().numpy(), 'prediction number')
print(test_y[:20].cpu().numpy(), 'real number')
- 代码执行结果:
- 关掉显示窗口后程序继续执行