def Conv1(in_planes, places, stride=2):
return nn.Sequential(
nn.Conv2d(in_channels=in_planes,out_channels=places,kernel_size=7,stride=stride,padding=3, bias=False),
nn.BatchNorm2d(places),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
)
class Bottleneck(nn.Module):
def __init__(self,in_places,places, stride=1,downsampling=False, expansion = 3):
super(Bottleneck,self).__init__()
self.expansion = expansion
#This expansion is to expand the number of channels in the 1*1 convolution to match the number of input channels in the next layer. 4*64=256
self.downsampling = downsampling
#Whether you need to down-sampling to jump the connection part, this mainly depends on the size of the neck network output and the size of the original image.
self.bottleneck = nn.Sequential(
nn.Conv2d(in_channels=10,out_channels=10,kernel_size=1,stride=1, bias=False),
nn.BatchNorm2d(10),
nn.ReLU(inplace=True),
nn.Conv2d(in_channels=10, out_channels=10, kernel_size=3, stride=stride, padding=1, bias=False),
nn.BatchNorm2d(10),
nn.ReLU(inplace=True),
#nn.Conv2d(in_channels=places, out_channels=places*self.expansion, kernel_size=1, stride=1, bias=False),
#nn.BatchNorm2d(places*self.expansion),
)
if self.downsampling:
self.downsample = nn.Sequential(
nn.Conv2d(in_channels=in_places, out_channels=places*self.expansion, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(places*self.expansion)
)
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
residual = x
out = self.bottleneck(x)
if self.downsampling:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self,blocks, num_classes=2, expansion = 2):
super(ResNet,self).__init__()
self.expansion = expansion
self.conv1 = Conv1(in_planes = 1, places= 10)
self.layer1 = self.make_layer(in_places = 10, places= 10, block=blocks[0], stride=1)
self.layer2 = self.make_layer(in_places = 10,places=10, block=blocks[1], stride=2)
#self.layer3 = self.make_layer(in_places=512,places=256, block=blocks[2], stride=2)
#self.layer4 = self.make_layer(in_places=1024,places=512, block=blocks[3], stride=2)
self.avgpool = nn.AvgPool2d(2, stride=1)
self.fc = nn.Linear(10,2)
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def make_layer(self, in_places, places, block, stride):
layers = []
layers.append(Bottleneck(in_places, places,stride, downsampling =True))
for i in range(1, block):
layers.append(Bottleneck(places*self.expansion, places))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.layer1(x)
x = self.layer2(x)
#x = self.layer3(x)
#x = self.layer4(x)
#x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
RuntimeError: The size of tensor a (10) must match the size of tensor b (30) at non-singleton dimension 1