# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python [conda env:for_torch]
#     language: python
#     name: conda-env-for_torch-py
# ---

# # A Simple Example on MNIST

# ### 导入模块

import torch, torchvision
from torchvision import transforms, datasets
from torch.utils.data import DataLoader
import torch.nn.functional as F
import torch.optim as optim

# ### 准备数据集

# +
batch_size = 256
transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.1307,),(0.3801, ))
])

train_dataset = datasets.MNIST(root='.\\data\\MNIST\\',
                             train=True,
                             download=True,
                             transform=transform)
train_loader = DataLoader(train_dataset,
                        shuffle=True,
                        batch_size=batch_size)

test_dataset = datasets.MNIST(root='.\\data\\MNIST\\',
                             train=False,
                             download=True,
                             transform=transform)
test_loader = DataLoader(train_dataset,
                        shuffle=False,
                        batch_size=batch_size)
# -

# `ToTensor()`将图像数据转变为张量，且读取顺序为 *C->W->H* 即通道值在前，随后为宽度与高度，`Normalize()`中前一个数据为均值，后一个数据为标准差，将原图像数据映射为 *N(0,1)* 标准正态分布

# ### 数据可视化

# 需要用到`np.transpose()`将原图像通道交换至最后一个维度变为 （w-h-c）

# +
import matplotlib.pyplot as plt
import numpy as np

def imshow(img):
    img = img*0.3801 + 0.1307
    npimg = img.numpy()
    plt.imshow(np.transpose(npimg, (1, 2, 0)))
    plt.show()

dataiter = iter(train_loader)
data, labels = dataiter.next()
data = data*0.3801 + 0.1307
imshow(torchvision.utils.make_grid(data))

# -

# ### 定义网络

# +
from torch.nn import Module, Linear, CrossEntropyLoss
class Net(Module):
    def __init__(self):
        super(Net, self).__init__()
        self.l1 = Linear(28*28, 512)
        self.l2 = Linear(512, 256)
        self.l3 = Linear(256, 128)
        self.l4 = Linear(128, 64)
        self.l5 = Linear(64, 10)
        
    def forward(self, x):
        x = x.view(-1, 28*28)
        x = F.relu(self.l1(x))
        x = F.relu(self.l2(x))
        x = F.relu(self.l3(x))
        x = F.relu(self.l4(x))
        return self.l5(x)
    
net = Net()
criterion = CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
# -

# ### 训练与验证网络

# +
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
net.to(device)
def train(epoch):
    running_loss = 0.
    for batch_idx, data in enumerate(train_loader, 0):
        inputs, target = data[0].to(device), data[1].to(device)
        optimizer.zero_grad()
        
        #更新网络
        outputs = net(inputs)
        loss = criterion(outputs, target)
        loss.backward()
        optimizer.step()
        
        running_loss += loss.item()
        
        if batch_idx % 200 == 199:
            print('[%d, %5d] loss: %.3f' % (epoch+1, batch_idx+1, running_loss/500))
            running_loss = 0.
            
def test():
    correct = 0
    total = 0
    with torch.no_grad():
        for data in test_loader:
            images, labels = data[0].to(device), data[1].to(device)
            outputs = net(images)
            _, predicted = torch.max(outputs.data, dim=1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()
    print('Accuracy on test set: %d %%'%(100*correct/total))


# -

for epoch in range(10):
    train(epoch)
    test()
print('training finished')

# +
available_gpus = [torch.cuda.device(i) for i in range(torch.cuda.device_count())]
print(available_gpus)


# 获取可用数量
print(torch.cuda.device_count())
print(torch.cuda.get_device_name(0))

StarcoderdataJupyterScriptsDedupFiltered