# 神經網絡學習-CNN（五）

## 爲什麼要用CNN

• 檢測上圖的鳥嘴，不需要看整張圖，只需要看鳥嘴的地方就可以了。
• Subsampling the pixels will not change the object
• 同樣的特徵會出現在圖片的不同區域

## 計算過程

### 卷積

• 做內積
• 同樣的特徵可以被一個卷積發現

• 只有9個點傳遞到下一個節點，所以參數少
• 共享了所有的參數，所以參數更少

## 手寫數字識別PyTorch實現

``````import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
import numpy as np
print("PyTorch Version: ",torch.__version__)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 20, 5, 1) # 28 * 28 -> (28+1-5)->24*24
self.conv2 = nn.Conv2d(20, 50, 5, 1)
self.fc1 = nn.Linear(4*4*50, 500)  #全連接層
self.fc2 = nn.Linear(500, 10)

def forward(self, x):
x = F.relu(self.conv1(x)) # 20 * 24 * 24
x = F.max_pool2d(x, 2, 2) # 12 * 12
x = F.relu(self.conv2(x)) # 8 * 8      12-5+1 = 8
x = F.max_pool2d(x, 2, 2) # 4 * 4
x = x.view(-1, 4*4*50)  #reshape(5,2,10),view(5,20)->5*20
x = F.relu(self.fc1(x))
x = self.fc2(x)
return F.log_softmax(x, dim=1)

def train(model, device, train_loader, optimizer, epoch, log_interval=100):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
output = model(data)
loss = F.nll_loss(output, target)
loss.backward()
optimizer.step()
if batch_idx % log_interval == 0:
print("Train Epoch: {} [{}/{} ({:0f}%)]\tLoss: {:.6f}".format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()
))
def test(model, device, test_loader):
model.eval()
test_loss = 0
correct = 0
for data, target in test_loader:
data, target = data.to(device), target.to(device)
output = model(data)
test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss
pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability
correct += pred.eq(target.view_as(pred)).sum().item()

print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
100. * correct / len(test_loader.dataset)))
torch.manual_seed(53113)

use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
batch_size = test_batch_size = 32
kwargs = {'num_workers': 40, 'pin_memory': True} if use_cuda else {}
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=batch_size, shuffle=True, **kwargs)
datasets.MNIST('./mnist_data', train=False, transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=test_batch_size, shuffle=True, **kwargs)

lr = 0.01
momentum = 0.5
model = Net().to(device)
optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum)

epochs = 2
for epoch in range(1, epochs + 1):
train(model, device, train_loader, optimizer, epoch)