pytorch框架下的Finetune 以及ResNet50 代码

 

  1.  Resnet 50
# -*- coding: utf-8 -*-

import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo


class residual_block(nn.Module):
    expansion = 4
    def __init__(self, inplanes, planes, stride=1, downsample = None):
        super(residual_block, self).__init__()
        self.conv1 = nn.Conv2d(inplanes, planes,  bias=False, kernel_size=1)
        self.bn1 = nn.BatchNorm2d(planes)
        self.conv2 = nn.Conv2d(planes, planes, stride = stride, kernel_size=3 , padding=1, bias = False)
        self.bn2 = nn.BatchNorm2d(planes)
        self.conv3 = nn.Conv2d(planes, planes*4,  kernel_size=1,bias=False)
        self.bn3 = nn.BatchNorm2d(planes * 4)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride


    def forward(self, x):
        residual = x

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

        conv2 = self.conv2(relu1)
        bn2 = self.bn2(conv2)
        relu2 = self.relu(bn2)

        conv3 = self.conv3(relu2)
        bn3 = self.bn3(conv3)
        if self.downsample is not None:
            residual = self.downsample(x)
        bn3 += residual
        out = self.relu(bn3)

        return out





class Resnet(nn.Module):
    def __init__(self,  layers, numclass):
        self.inplanes = 64
        super(Resnet, self).__init__() ## super函数是用于调用父类(超类)的一个方法
        self.conv1 = nn.Conv2d(in_channels=3, out_channels=64, kernel_size=7, stride=2,
                               padding=3, bias=False)
        self.bn1 = nn.BatchNorm2d(num_features=64)
        self.relu = nn.ReLU(inplace=True)   ##inplace为True,将会改变输入的数据 ,否则不会改变原输入,只会产生新的输出
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self._make_layer(residual_block, 64, blocks = layers[0], stride=1)
        self.layer2 = self._make_layer(residual_block, 128, blocks = layers[1], stride=2)
        self.layer3 = self._make_layer(residual_block, 256, blocks = layers[2], stride=2)
        self.layer4 = self._make_layer(residual_block, 512, blocks = layers[3], st
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值