卷积神经网络高级篇

为了避免重复地进行神经网络的定义,把一些重复的封装成类,提高效率。至于对应的通道数,可以一层一层定义,定义完后输出结果的shape,来进行下一层输入的确定

import numpy as np
import torch
import matplotlib.pyplot as plt
from torchvision import transforms
import torch.nn.functional as F
from torchvision import datasets #与Datasets类相比,不用实现里面的函数,直接就可以取出里面的(x,y)
from torch.utils.data import DataLoader


batch_size = 64
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
#transforms.ToTensor()将数据从[0,255]范围转换到[0,1],图像转张量,transforms.Normalize是归一化,后面参数是均值和标准差

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


class InceptionA(torch.nn.Module):
    def __init__(self,in_channels):
        super(InceptionA,self).__init__()
        self.branch1x1 = torch.nn.Conv2d(in_channels, 16, kernel_size=1)

        self.branch5x5_1 = torch.nn.Conv2d(in_channels, 16, kernel_size=1)
        self.branch5x5_2 = torch.nn.Conv2d(16, 24, kernel_size=5, padding=2)

        self.branch3x3_1 = torch.nn.Conv2d(in_channels, 16, kernel_size=1)
        self.branch3x3_2 = torch.nn.Conv2d(16, 24, kernel_size=3, padding=1)
        self.branch3x3_3 = torch.nn.Conv2d(24, 24, kernel_size=3, padding=1)

        self.branch_pool = torch.nn.Conv2d(in_channels, 24, kernel_size=1)

    def forward(self,x):
        branch1x1 = self.branch1x1(x)

        branch5x5 = self.branch5x5_1(x)
        branch5x5 = self.branch5x5_2(branch5x5)

        branch3x3 = self.branch3x3_1(x)
        branch3x3 = self.branch3x3_2(branch3x3)
        branch3x3 = self.branch3x3_3(branch3x3)

        branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)
        branch_pool = self.branch_pool(branch_pool)

        outputs = [branch1x1, branch5x5, branch3x3, branch_pool]
        return torch.cat(outputs, dim=1)  # b,c,w,h  c对应的是dim=1



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(88, 20, kernel_size=5)
        self.incept1 = InceptionA(in_channels=10)
        self.incept2 = InceptionA(in_channels=20)
        self.mp = torch.nn.MaxPool2d(2)
        self.fc = torch.nn.Linear(1408,10)

    def forward(self,x):
        batch_size = x.size(0)
        x = F.relu(self.mp(self.conv1(x)))
        x = self.incept1(x)
        x = F.relu(self.mp(self.conv2(x)))
        x = self.incept2(x)
        x = torch.flatten(x,1)
        x = self.fc(x)

        return x

model = Net()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)

criterion = torch.nn.CrossEntropyLoss(reduction='mean') #交叉熵
optimizer = torch.optim.SGD(model.parameters(), lr=0.01,momentum=0.5)

def train(epoch):
    sum_loss = 0
    for i,data in enumerate(train_loader, 0):
        inputs,labels = data #inputs是一个batch的输入
        #print(i,inputs.size())
        inputs, labels = inputs.to(device), labels.to(device)
        y_pred = model(inputs)
        loss = criterion(y_pred,labels)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        sum_loss+=loss.item()
        if(i%300==299):
            print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, sum_loss / 300))
            sum_loss = 0.0

def t():
    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)  # dim = 1 列是第0个维度,行是第1个维度
            #_是无用变量,占位的,因为第一个返回值是最大值,predicted是最大值的下标,只需要第二个变量
            total += labels.size(0)
            correct += (predicted == labels).sum().item()  # 张量之间的比较运算
    print('accuracy on test set: %d %% ' % (100 * correct / total))
    return correct/total


epoch_list = []
acc_list = []

if __name__ == '__main__':
    for epoch in range(8):
        train(epoch)
        acc = t()
        epoch_list.append(epoch)
        acc_list.append(acc)

    plt.plot(epoch_list, acc_list)
    plt.ylabel('accuracy')
    plt.xlabel('epoch')
    plt.show()

为了避免梯度消失和梯度爆炸,用residual net来解决。residual net前后w,h不能变,所以不可以用池化层。

 

import numpy as np
import torch
import matplotlib.pyplot as plt
from torchvision import transforms
import torch.nn.functional as F
from torchvision import datasets #与Datasets类相比,不用实现里面的函数,直接就可以取出里面的(x,y)
from torch.utils.data import DataLoader


batch_size = 64
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
#transforms.ToTensor()将数据从[0,255]范围转换到[0,1],图像转张量,transforms.Normalize是归一化,后面参数是均值和标准差

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


class ResidualBlock(torch.nn.Module):
    def __init__(self, channels):
        super(ResidualBlock, self).__init__()
        self.conv1 = torch.nn.Conv2d(channels, channels, kernel_size=3, padding=1)
        self.conv2 = torch.nn.Conv2d(channels, channels, kernel_size=3, padding=1)

    def forward(self, x):
        y = F.relu(self.conv1(x))
        y = self.conv2(y)
        return F.relu(x + y)




class Net(torch.nn.Module):
    def __init__(self):
        super(Net,self).__init__()
        self.conv1 = torch.nn.Conv2d(1,16,kernel_size=5)
        self.conv2 = torch.nn.Conv2d(16, 32, kernel_size=5)

        self.rblock1 = ResidualBlock(16)
        self.rblock2 = ResidualBlock(32)

        self.mp = torch.nn.MaxPool2d(2)
        self.fc = torch.nn.Linear(512,10)

    def forward(self,x):
        batch_size = x.size(0)
        x = F.relu(self.mp(self.conv1(x)))
        x = self.rblock1(x)
        x = F.relu(self.mp(self.conv2(x)))
        x = self.rblock2(x)
        x = torch.flatten(x,1)
        x = self.fc(x)

        return x

model = Net()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)

criterion = torch.nn.CrossEntropyLoss(reduction='mean') #交叉熵
optimizer = torch.optim.SGD(model.parameters(), lr=0.01,momentum=0.5)

def train(epoch):
    sum_loss = 0
    for i,data in enumerate(train_loader, 0):
        inputs,labels = data #inputs是一个batch的输入
        #print(i,inputs.size())
        inputs, labels = inputs.to(device), labels.to(device)
        y_pred = model(inputs)
        loss = criterion(y_pred,labels)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        sum_loss+=loss.item()
        if(i%300==299):
            print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, sum_loss / 300))
            sum_loss = 0.0

def t():
    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)  # dim = 1 列是第0个维度,行是第1个维度
            #_是无用变量,占位的,因为第一个返回值是最大值,predicted是最大值的下标,只需要第二个变量
            total += labels.size(0)
            correct += (predicted == labels).sum().item()  # 张量之间的比较运算
    print('accuracy on test set: %d %% ' % (100 * correct / total))
    return correct/total


epoch_list = []
acc_list = []

if __name__ == '__main__':
    for epoch in range(8):
        train(epoch)
        acc = t()
        epoch_list.append(epoch)
        acc_list.append(acc)

    plt.plot(epoch_list, acc_list)
    plt.ylabel('accuracy')
    plt.xlabel('epoch')
    plt.show()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值