《PyTorch深度学习实践》P10卷积神经网络基础篇CNN

全部代码在最后面。
基本模式:《PyTorch深度学习实践》P10卷积神经网络基础篇CNN_第1张图片
patch:
《PyTorch深度学习实践》P10卷积神经网络基础篇CNN_第2张图片

单通道,卷积做数乘:
《PyTorch深度学习实践》P10卷积神经网络基础篇CNN_第3张图片
先数乘再加:
《PyTorch深度学习实践》P10卷积神经网络基础篇CNN_第4张图片
每一个卷积核通道数量和输入通道数量一样!
卷积核总数量和输出通道数量一样!
卷积核数量和图片大小没关
《PyTorch深度学习实践》P10卷积神经网络基础篇CNN_第5张图片
想得到和原来一样的维度,padding怎么计算加外围多少层:(如图所示)
《PyTorch深度学习实践》P10卷积神经网络基础篇CNN_第6张图片

例子:
《PyTorch深度学习实践》P10卷积神经网络基础篇CNN_第7张图片
code:

在这里import torch

input = [3,4,6,5,7,
         2,4,6,8,2,
         1,6,7,8,4,
         9,7,4,6,2,
         3,7,5,4,1]
# (1(batch),1(channel),5(width),5(height))
input = torch.Tensor(input).view(1, 1, 5, 5)
# 输入:1个通道,输出:1个通道
conv_layer = torch.nn.Conv2d(1, 1, kernel_size = 3, padding = 1, bias = False)
# 用view改变形状 (1(output),1(input),3(width),3(height))
kernel = torch.Tensor([1,2,3,4,5,6,7,8,9]).view(1, 1, 3, 3)
#把张量赋给.data
conv_layer.weight.data = kernel.data

output = conv_layer(input)
print(output)

效果图:
《PyTorch深度学习实践》P10卷积神经网络基础篇CNN_第8张图片
步长:有效降低宽度,高度;
stride = 2
code:

conv_layer = torch.nn.Conv2d(1, 1, kernel_size = 3, stride=2, bias = False)

效果图:
《PyTorch深度学习实践》P10卷积神经网络基础篇CNN_第9张图片
《PyTorch深度学习实践》P10卷积神经网络基础篇CNN_第10张图片

maxpooling:没有权重,在同一个通道里面做,不会在不同通道里,使用后,通道数量不会变。
《PyTorch深度学习实践》P10卷积神经网络基础篇CNN_第11张图片
《PyTorch深度学习实践》P10卷积神经网络基础篇CNN_第12张图片
CNN:
《PyTorch深度学习实践》P10卷积神经网络基础篇CNN_第13张图片
code:(单独,不可直接运行)

import torch
class Net(torch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = torch.nn.Conv2d(1, 10, kernel_size=5)
        self.conv2 = torch.nn.Conv2d(10, 20, kernel_size=5)
        self.pooling = torch.nn.MaxPool2d(2)
        self.fc = torch.nn.Linear(320, 10) # 线性层

    def forward(self, x):
        # 先求batch_size,用张量.size()求,取第0个,即是维度(样本的数量)
        # Flatten data from (n, 1, 28, 28) to (n, 784)
        batch_size = x.size(0)
        x = F.relu(self.pooling(self.conv1(x)))
        x = F.relu(self.pooling(self.conv2(2)))
        x = x.view(batch_size, -1) # flatten 平铺
        x = self.fc(x)
        return x

model = Net()

总的code:

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

batch_size = 64
transforms = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.1307, ), (0.3081, )) # 第一个(0.1307, )是均值,第二个是标准差
])
train_dataset = datasets.MNIST(root='../dataset/mnist',
                               train=True,
                               download=True,
                               transform=transforms)
train_loader = DataLoader(train_dataset,
                          shuffle=True,
                          batch_size=batch_size)

test_dataset = datasets.MNIST(root='../dataset/mnist',
                              train=False,
                              download=True,
                              transform=transforms)
test_loader = DataLoader(test_dataset,
                         shuffle=False,
                         batch_size=batch_size)

class Net(torch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = torch.nn.Conv2d(1, 10, kernel_size=5)
        self.conv2 = torch.nn.Conv2d(10, 20, kernel_size=5)
        self.pooling = torch.nn.MaxPool2d(2)
        self.fc = torch.nn.Linear(320, 10) # 线性层

    def forward(self, x):
        # 先求batch_size,用张量.size()求,取第0个,即是维度(样本的数量)
        # Flatten data from (n, 1, 28, 28) to (n, 784)
        batch_size = x.size(0)
        x = F.relu(self.pooling(self.conv1(x)))
        x = F.relu(self.pooling(self.conv2(x)))
        x = x.view(batch_size, -1) # flatten 平铺 # -1 此处自动算出的是320
        # print("x.shape",x.shape)
        x = self.fc(x)
        return x

model = Net()

# 使用GPU
if torch.cuda.is_available():
    device = "cuda:0"
else:
    device = "cpu"
device = torch.device(device)
model.to(device)

criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)

def train(epoch):
    running_loss = 0.0
    for batch_idx, data in enumerate(train_loader, 0):
#        X:inputs,Y:target
        inputs, target = data
        inputs, target = inputs.to(device), target.to(device)
        optimizer.zero_grad()

        # 前向+反向+更新
        outputs = model(inputs)
        loss = criterion(outputs, target)
        loss.backward()
        optimizer.step()

        running_loss += loss.item()
        if batch_idx % 300 == 299:
            print('[%d, %5d] loss: %.3f' % (epoch +1, batch_idx +1, running_loss / 300))
            running_loss = 0.0

def test():
    correct = 0
    total = 0
    with torch.no_grad():
        for data in test_loader:
            images, labels = data
            images, labels = images.to(device), labels.to(device)
            outputs = model(images)
            _, predicted = torch.max(outputs.data, dim=1) # 算每一行最大值的下标是多少,其实也代表了每一行的分类 / max返回 每一行最大值是多少,每一行最大值的下标是多少
            total += labels.size(0)
            correct += (predicted == labels).sum().item() # ==预测的和原来的作比较,真为1,假为0,再总的加起来,求和后再把这个标量提出来
    print('Accuracy on test set: %d %%' % (100 * correct / total))

if __name__ == '__main__':
    for epoch in range(10):
        train(epoch)
        test()

效果图:
《PyTorch深度学习实践》P10卷积神经网络基础篇CNN_第14张图片

你可能感兴趣的:(pytorch,pytorch,深度学习,cnn)