#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
 @Time    : 2018/11/1 20:28
@Author  : LI Zhe
"""
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms

# 配置设备
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# 定义网络参数
num_classes = 10
num_epochs = 1
batch_size = 100
learning_rate = 0.001

# MNIST dataset
train_dataset  = torchvision.datasets.MNIST(root='./../data/MNIST',
                                            train=True,
                                            transform=transforms.ToTensor(),
                                            download=True)
test_dataset  = torchvision.datasets.MNIST(root='./../data/MNIST',
                                            train=False,
                                            transform=transforms.ToTensor())

# 定义数据集加载函数 Data loader
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
                                           batch_size=batch_size,
                                           shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
                                           batch_size=batch_size,
                                           shuffle=True)

# 卷积神经网络
class ConvNet(nn.Module):
    def __init__(self, num_classes=10):
        super(ConvNet, self).__init__()
        self.layer1 = nn.Sequential(
            # input channel(C_in), output channel(C_out) C_in * H * W
            # H_out = (H - kernel_size + 2 * padding) / stride + 1 
            nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),
            nn.BatchNorm2d(16),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2)
        )
        self.layer2 = nn.Sequential(
            nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2),
            nn.BatchNorm2d(32),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2)
        )
        self.fc = nn.Linear(7* 7 * 32, num_classes)

    def forward(self,x):
        out = self.layer1(x)
        out = self.layer2(out)
        out = out.reshape(out.size(0), -1)
        out = self.fc(out)
        return out

model = ConvNet(num_classes).to(device)

# loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

# Train the model
total_steps = len(train_loader)
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        #  reshape images to (batch, input_size)
        # print(images.shape)
        images = images.to(device)
        labels = labels.to(device)

        # forward pass
        outputs = model(images)
        # print(outputs.shape)
        loss = criterion(outputs, labels)

        # backward pass
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if (i + 1) % 100 == 0:
            print('Epoch:[{}/{}], Step:[{}/{}],loss:{:.4f}'.format(epoch+1,num_epochs,i+1,total_steps,loss.item()))

# Test model
model.eval()
# eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance)
with torch.no_grad():
    correct = 0
    total = 0
    for i, (images, labels) in enumerate(test_loader):
        #  reshape images to (batch, input_size)
        images = images.to(device)
        labels = labels.to(device)

        # forward pass
        outputs = model(images)
        # print(outputs.data.shape, type(outputs.data))
        # print(outputs.shape, type(outputs))

        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()
        print('Accuracy of the model on the 100 test images: {}%'.format(100 * correct / total))

# Save the model checkpoint
torch.save(model.state_dict(), 'model.ckpt')