Files
ieemoo-ai-conpurchase/network/BaseNet.py
2023-08-17 11:21:39 +08:00

181 lines
6.2 KiB
Python

import torch
from torch import nn
import torch.nn.init as init
import torch.nn.functional as F
import torchvision.models as models
from PIL import Image
import torchvision.transforms as transforms
#from network import GeM as gem
import torch.nn.functional as F
class channelAttention(nn.Module):
def __init__(self, channel, reduction=16):
super(channelAttention, self).__init__()
self.Maxpooling = nn.AdaptiveMaxPool2d(1)
self.Avepooling = nn.AdaptiveAvgPool2d(1)
self.ca = nn.Sequential()
self.ca.add_module('conv1',nn.Conv2d(channel, channel//reduction, 1, bias=False))
self.ca.add_module('Relu', nn.ReLU())
self.ca.add_module('conv2',nn.Conv2d(channel//reduction, channel, 1, bias=False))
self.sigmod = nn.Sigmoid()
def forward(self, x):
M_out = self.Maxpooling(x)
A_out = self.Avepooling(x)
M_out = self.ca(M_out)
A_out = self.ca(A_out)
out = self.sigmod(M_out+A_out)
return out
class SpatialAttention(nn.Module):
def __init__(self, kernel_size=7):
super().__init__()
self.conv = nn.Conv2d(in_channels=2, out_channels=1, kernel_size=kernel_size, padding=kernel_size // 2)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
max_result, _ = torch.max(x, dim=1, keepdim=True)
avg_result = torch.mean(x, dim=1, keepdim=True)
result = torch.cat([max_result, avg_result], dim=1)
output = self.conv(result)
output = self.sigmoid(output)
return output
class CBAM(nn.Module):
def __init__(self, channel=512, reduction=16, kernel_size=7):
super().__init__()
self.ca = channelAttention(channel, reduction)
self.sa = SpatialAttention(kernel_size)
def init_weights(self):
for m in self.modules():#权重初始化
if isinstance(m, nn.Conv2d):
init.kaiming_normal_(m.weight, mode='fan_out')
if m.bias is not None:
init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
init.constant_(m.weight, 1)
init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
init.normal_(m.weight, std=0.001)
if m.bias is not None:
init.constant_(m.bias, 0)
def forward(self, x):
# b,c_,_ = x.size()
# residual = x
out = x*self.ca(x)
out = out*self.sa(out)
return out
class GeM(nn.Module):
def __init__(self, p=3, eps=1e-6):
super(GeM, self).__init__()
self.p = nn.Parameter(torch.ones(1) * p)
self.eps = eps
def forward(self, x):
return self.gem(x, p=self.p, eps=self.eps)
def gem(self, x, p=3, eps=1e-6):
#return F.avg_pool2d(x.clamp(min=eps).pow(p), (x.size(-2), x.size(-1))).pow(1. / p)
return F.avg_pool2d(x.clamp(min=eps).pow(p), (7, 7)).pow(1. / p)
def __repr__(self):
return self.__class__.__name__ + \
'(' + 'p=' + '{:.4f}'.format(self.p.data.tolist()[0]) + \
', ' + 'eps=' + str(self.eps) + ')'
class ResnetFpn(nn.Module):
def __init__(self):
super(ResnetFpn, self).__init__()
self.model = models.resnet50()
self.conv1 = nn.Conv2d(in_channels=2048, out_channels=256, kernel_size=1, stride=1, padding=0)
self.conv2 = nn.Conv2d(1024, 256, 1, 1, 0)
self.conv3 = nn.Conv2d(512, 256, 1, 1, 0)
self.conv4 = nn.Conv2d(256, 256, 1, 1, 0)
self.fpn_convs = nn.Conv2d(256, 256, 3, 1, 1)
self.pool = nn.AvgPool2d(7, 7, padding=2)
#self.gem = GeM()
#self.in_channel = 64
self.cbam_layer1 = CBAM(256)
self.cbam_layer2 = CBAM(512)
self.cbam_layer3 = CBAM(1024)
self.cbam_layer4 = CBAM(2048)
self.fc = nn.Linear(in_features=20736, out_features=2048)
self.fc1 = nn.Linear(2048, 1024)
self.fc2 = nn.Linear(1024, 512)
self.fc3 = nn.Linear(512, 128)
def forward(self, x):
x = self.model.conv1(x)
x = self.model.bn1(x)
x = self.model.relu(x)
x = self.model.maxpool(x)
layer1 = self.model.layer1(x)
layer1 = self.cbam_layer1(layer1)
#print('layer1 >>> {}'.format(layer1.shape))
layer2 = self.model.layer2(layer1)
layer2 = self.cbam_layer2(layer2)
#print('layer2 >>> {}'.format(layer2.shape))
layer3 = self.model.layer3(layer2)
layer3 = self.cbam_layer3(layer3)
#print('layer3 >>> {}'.format(layer3.shape))
layer4 = self.model.layer4(layer3) # channel 256 512 1024 2048
layer4 = self.cbam_layer4(layer4)
#print('layer4 >>> {}'.format(layer4.shape))
P5 = self.conv1(layer4)
P4_ = self.conv2(layer3)
P3_ = self.conv3(layer2)
P2_ = self.conv4(layer1)
size4 = P4_.shape[2:]
size3 = P3_.shape[2:]
size2 = P2_.shape[2:]
P4 = P4_ + F.interpolate(P5, size=size4, mode='nearest')
P3 = P3_ + F.interpolate(P4, size=size3, mode='nearest')
P2 = P2_ + F.interpolate(P3, size=size2, mode='nearest')
P5 = self.fpn_convs(P5)
P4 = self.fpn_convs(P4)
P3 = self.fpn_convs(P3)
P2 = self.fpn_convs(P2)
output = self.pool(P2)
#output = self.gem(P2)
#input_dim = len(output.view(-1))
#output = output.view(output.size(0), -1)
output = output.contiguous().view(output.size(0), -1)
output = self.fc(output)
output = self.fc1(output)
output = self.fc2(output)
output = self.fc3(output)
return output
if __name__ == '__main__':
img_path = '600.jpg'
img = Image.open('600.jpg')
# if img.mode != 'L':
# img = img.convert('L')
#img = img.resize((256, 256))
transform = transforms.Compose([transforms.Resize((256,256)),
transforms.ToTensor()])
img = transform(img)
img = img.cuda()
# from torchsummary import summary
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = ResnetFpn().to(device)
model.eval()
img = torch.unsqueeze(img, dim=0).float()
# images, targets = model.transform(images, targets=None)
result = model(img)
#print('result >>> {} >>{}'.format(result, result.size()))