4 ResNet 分类

1、原理介绍

https://blog.csdn.net/csdnldp/article/details/78313087?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522159851730119724811822972%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=159851730119724811822972&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_click~default-1-78313087.pc_ecpm_v3_pc_rank_v3&utm_term=resnet&spm=1018.2118.3001.4187

2、model.py

import torch.nn as nn
import torch


# 【1】定义18/34层的残差结构;这个模块不仅需要有实线残差功能,还要有虚线的功能
class BasicBlock(nn.Module):

    # 18/34层的残差结构,他的第一层与第二层的卷积核的个数是一样的
    expansion = 1    # 对应的残差结构主分支上所采用的卷积核的个数有没有发生变化。

# downsample所对应的就是虚线的残差结构---shortcut,1*1的卷积层;out_channel主分支上卷积核的个数(输出深度)
# in_channel 输入的深度

# conv3_x---conv5_x的第一层残差结构,都是虚线残差结构--》每一层都起到降维的作用
    def __init__(self, in_channel, out_channel, stride=1, downsample=None):
        super(BasicBlock, self).__init__()

        # stride是传入的参数,默认=1,时对应的是实线残差结构,=2时对应虚线残差结构---》h w 变为一半; bias=False不使用偏置参数,因为BN
        # 输出的深度=in_channel(传入的),out_channel(传入的)
        self.conv1 = nn.Conv2d(in_channels=in_channel, out_channels=out_channel,
                               kernel_size=3, stride=stride, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(out_channel)
        self.relu = nn.ReLU()

        # 无论是实线还是虚线残差结构,第二层卷积中stride=1
        # 输入是conv1的输出out_channel,卷积核的个数是out_channel
        self.conv2 = nn.Conv2d(in_channels=out_channel, out_channels=out_channel,
                               kernel_size=3, stride=1, padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(out_channel)
        self.downsample = downsample            # 默认=none

# 【2】定义前向传播
    def forward(self, x):
        identity = x    # identity捷径分支上的输出值

        # 如果有输入下采样函数(not None),则对应的是虚线的残差结构x输入--》得到捷径分支的输出
        if self.downsample is not None:
            identity = self.downsample(x)

#        主线的输入
        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

#       主分支与捷径分支相加
        out += identity
        out = self.relu(out)

        return out



#【3】定义50/101/152层的残差结构
class Bottleneck(nn.Module):
    expansion = 4           #conv2_x--conv5_x中,第三层的卷积核的个数是前两层的4倍

    def __init__(self, in_channel, out_channel, stride=1, downsample=None):
        super(Bottleneck, self).__init__()

        # 卷积核的个数out_channel(输入的)指的是残差结构中第一,第二层的卷积核的个数
        self.conv1 = nn.Conv2d(in_channels=in_channel, out_channels=out_channel,
                               kernel_size=1, stride=1, bias=False)  # squeeze channels
        self.bn1 = nn.BatchNorm2d(out_channel)
        # -----------------------------------------
        # 卷积层第二层,实现残差结构中stride=1,虚线残差中stride=2,stride=stride是传入参数,默认为1
        self.conv2 = nn.Conv2d(in_channels=out_channel, out_channels=out_channel,
                               kernel_size=3, stride=stride, bias=False, padding=1)
        self.bn2 = nn.BatchNorm2d(out_channel)
        # -----------------------------------------
        # out_channels=out_channel*self.expansion 卷积核的个数是上一层卷积核的4倍
        self.conv3 = nn.Conv2d(in_channels=out_channel, out_channels=out_channel*self.expansion,
                               kernel_size=1, stride=1, bias=False)  # unsqueeze channels
        self.bn3 = nn.BatchNorm2d(out_channel*self.expansion)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample

# 【4】定义前向传播
    def forward(self, x):
        identity = x
        if self.downsample is not None:
            identity = self.downsample(x)

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        out += identity
        out = self.relu(out)

        return out

# 【5】整个框架的部分
class ResNet(nn.Module):

# block 所对应的就是残差结构, blocks_num 所使用残差结构的数目 是一个列表结构, include_top=True方便以后在resnet上搭建更加复杂的网络
    def __init__(self, block, blocks_num, num_classes=1000, include_top=True):
        super(ResNet, self).__init__()
        self.include_top = include_top
        self.in_channel = 64
        # 是通过第一层的池化的深度,--》所有层残差结构在maxpool后输出都为64


# 对应表格7*7卷积层,第一层使用的卷积核的个数是64个=self.in_channel
        self.conv1 = nn.Conv2d(3, self.in_channel, kernel_size=7, stride=2,
                               padding=3, bias=False)
        self.bn1 = nn.BatchNorm2d(self.in_channel)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)

       # conv2_x---conv5_x;是通过self._make_layer函数生成的;64 128 256 等都是conv2_x---conv5_x第一层卷积核的 个数
        self.layer1 = self._make_layer(block, 64, blocks_num[0])
        self.layer2 = self._make_layer(block, 128, blocks_num[1], stride=2)
        self.layer3 = self._make_layer(block, 256, blocks_num[2], stride=2)
        self.layer4 = self._make_layer(block, 512, blocks_num[3], stride=2)
        if self.include_top:
            self.avgpool = nn.AdaptiveAvgPool2d((1, 1))  # output size = (1, 1)
            self.fc = nn.Linear(512 * block.expansion, num_classes)

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')

# block(BasicBlock/Bottleneck) , channel 残差结构中第一层卷积核个数, block_num 该层(conv2_X)一共有多少个残差结构
# 34层中 conv_2x是3个, stride=1
#
# stride从第二层开始就变成2,所以都会生层虚线残差结构
    def _make_layer(self, block, channel, block_num, stride=1):
        downsample = None

        # 对于第1层stride默认为1,in_channel=64(定义的)是否与channel * block.expansion相等。
        # 对于layer1是不满足的,64=64*1 ;所以对于18/34层会直接跳过这个语句;
        # 对于50/101/152是满足,则会进入语句生成downsample---》在conv2_x所对应的一系列残差结构的第一层其实也是虚线的残差结构,
        # 但是只需要调整特征矩阵的深度,h w 则不需要调整。
        # 对于conv3_x---conv5_x对应的第一层虚线残差结构,不仅要调整深度,还要将h w 变为原来一半
        if stride != 1 or self.in_channel != channel * block.expansion:
            downsample = nn.Sequential(
                # 捷径分支*4
                nn.Conv2d(self.in_channel, channel * block.expansion, kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(channel * block.expansion))

        layers = []

        # 将第一层的残差结构添加进layers,channel残差结构所对应分支上的第一个卷积层的卷积核的个数
        #  downsample=downsample 对于18/34层的网络由于他是=none,所对应的就是一个实线的残差结构
        # 对于50/101/152层而言它的downsample是我们定义好的深度*4,h w不变---》所对应的就是虚线残差结构
        # 对于layer1来说stride=1
        layers.append(block(self.in_channel, channel, downsample=downsample, stride=stride))
        self.in_channel = channel * block.expansion

        # 遍历实线残差结构,无论是18/152的残差结构中第二层卷积开始都是实线结构
        # 1 从1开始,因为第一层已经搭建好了, block_num
        for _ in range(1, block_num):
            layers.append(block(self.in_channel, channel))

        # 把列表转换成非关键字参数传进去
        return nn.Sequential(*layers)

# 【6】总体的前向传播
    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        if self.include_top:
            x = self.avgpool(x)
            x = torch.flatten(x, 1)
            x = self.fc(x)

        return x


def resnet34(num_classes=1000, include_top=True):
    return ResNet(BasicBlock, [3, 4, 6, 3], num_classes=num_classes, include_top=include_top)


def resnet101(num_classes=1000, include_top=True):
    return ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes, include_top=include_top)

3、train.py

import torch
import torch.nn as nn
from torchvision import transforms, datasets
import json
import matplotlib.pyplot as plt
import os
import torch.optim as optim
from model import resnet34, resnet101



device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)

data_transform = {
    "train": transforms.Compose([transforms.RandomResizedCrop(224),
                                 transforms.RandomHorizontalFlip(),
                                 transforms.ToTensor(),
                                 transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]),
    "val": transforms.Compose([transforms.Resize(256),
                               transforms.CenterCrop(224),
                               transforms.ToTensor(),
                               transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])}


data_root = os.path.abspath(os.path.join(os.getcwd(), "../.."))  # get data root path
image_path = data_root + "/data_set/gabage_data/"  # flower data set path

train_dataset = datasets.ImageFolder(root=image_path+"train",
                                     transform=data_transform["train"])
train_num = len(train_dataset)

# {'daisy':0, 'dandelion':1, 'roses':2, 'sunflower':3, 'tulips':4}
flower_list = train_dataset.class_to_idx
cla_dict = dict((val, key) for key, val in flower_list.items())
# write dict into json file
json_str = json.dumps(cla_dict, indent=4)
with open('class_indices.json', 'w') as json_file:
    json_file.write(json_str)

batch_size = 16
train_loader = torch.utils.data.DataLoader(train_dataset,
                                           batch_size=batch_size, shuffle=True,
                                           num_workers=0)

validate_dataset = datasets.ImageFolder(root=image_path + "val",
                                        transform=data_transform["val"])
val_num = len(validate_dataset)
validate_loader = torch.utils.data.DataLoader(validate_dataset,
                                              batch_size=batch_size, shuffle=False,
                                              num_workers=0)

# 【1】net = GoogLeNet(num_classes=5, aux_logits=True, init_weights=True)
# net.to(device)

# 【2】 net = AlexNet(num_classes=12, init_weights=True)
#  网络指定到规定的设备中
#  net.to(device)
net = resnet34(num_classes=12)
net.to(device)

# {net = resnet34()
# # # net.load_state_dict(torch.load;load pretrain weights
# model_weight_path = "./resnet34-333f7ec4.pth"
# missing_keys, unexpected_keys = net.load_state_dict(torch.load(model_weight_path), strict=False)
# # # for param in net.parameters():
# # #     param.requires_grad = False
# # # change fc layer structure
# inchannel = net.fc.in_features
# net.fc = nn.Linear(inchannel, 5)
# net.to(device)}

loss_function = nn.CrossEntropyLoss()
optimizer = optim.Adam(net.parameters(), lr=0.0001)

best_acc = 0.0
save_path = './resNet34.pth'
for epoch in range(200):
    # train
    net.train()
    running_loss = 0.0
    for step, data in enumerate(train_loader, start=0):
        images, labels = data
        optimizer.zero_grad()
        logits = net(images.to(device))
        loss = loss_function(logits, labels.to(device))
        loss.backward()
        optimizer.step()

        # print statistics
        running_loss += loss.item()
        # print train process
        rate = (step+1)/len(train_loader)
        a = "*" * int(rate * 50)
        b = "." * int((1 - rate) * 50)
        print("\rtrain loss: {:^3.0f}%[{}->{}]{:.4f}".format(int(rate*100), a, b, loss), end="")
    print()

    # validate
    net.eval()
    acc = 0.0  # accumulate accurate number / epoch
    with torch.no_grad():
        for data_test in validate_loader:
            test_images, test_labels = data_test
            outputs = net(test_images.to(device))  # eval model only have last output layer
            # loss = loss_function(outputs, test_labels)
            predict_y = torch.max(outputs, dim=1)[1]
            acc += (predict_y == test_labels.to(device)).sum().item()
        val_accurate = acc / val_num
        if val_accurate > best_acc:
            best_acc = val_accurate
            torch.save(net.state_dict(), save_path)
        print('[epoch %d] train_loss: %.3f  test_accuracy: %.3f' %
              (epoch + 1, running_loss / step, val_accurate))

print('Finished Training')

4、predict.py

import torch
from model import resnet34
from PIL import Image
from torchvision import transforms
import matplotlib.pyplot as plt
import json

# 要进行和训练过程一样的预处理
data_transform = transforms.Compose(
    [transforms.Resize(256),
     transforms.CenterCrop(224),
     transforms.ToTensor(),
     transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])

# load image
img = Image.open("../tulip.jpg")
plt.imshow(img)
# [N, C, H, W]
img = data_transform(img)
# expand batch dimension
img = torch.unsqueeze(img, dim=0)

# read class_indict
try:
    json_file = open('./class_indices.json', 'r')
    class_indict = json.load(json_file)
except Exception as e:
    print(e)
    exit(-1)

# create model
model = resnet34(num_classes=5)
# load model weights
model_weight_path = "./resNet34.pth"
model.load_state_dict(torch.load(model_weight_path))
model.eval()
with torch.no_grad():
    # predict class
    output = torch.squeeze(model(img))
    predict = torch.softmax(output, dim=0)
    predict_cla = torch.argmax(predict).numpy()
print(class_indict[str(predict_cla)], predict[predict_cla].numpy())
plt.show()

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值