Darknet网络代码
import math
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
class Mish(nn.Module):
def __init__(self):
super(Mish, self).__init__()
def forward(self, x):
x = x * torch.tanh(F.softmax(x))
# F.softmax(x) = ln(1+e^x)
# tanh(x) = (e^x-e^(-x))/(e^x+e^(-x))
return x
# 卷积+归一化+激活
class CB(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1):
super(CB, self).__init__()
self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=kernel_size // 2, bias=False)
self.bn = nn.BatchNorm2d(out_channels)
self.activation = Mish()
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
x = self.activation(x)
return x
class Resblock(nn.Module):
def __init__(self, channels, hidden_channels=None):
super(Resblock, self).__init__()
if hidden_channels is None:
hidden_channels = channels
self.resblock = nn.Sequential(
nn.Conv2d(in_channels = channels, out_channels= hidden_channels, kernel_size=1),
nn.Conv2d(in_channels=hidden_channels, out_channels=channels, kernel_size=3, padding=1)
)
def forward(self, x):
x = x + self.resblock(x)
return x
class Resblock_body(nn.Module):
def __init__(self, in_channels, out_channels, num_blocks, first):
super(Resblock_body, self).