Shengzhen's picture
Upload 15 files
9f97959 verified
Raw History Blame Contribute Delete
20.7 kB
import numpy as np
from torch.nn.utils.rnn import pad_sequence
import torch
import torch.nn as nn
import torchvision.models as models
from torchvision.models.inception import Inception_V3_Weights
class pln(nn.Module):
def __init__(self, s, b,num_classes,pretrain=True):
"""
return: [s, s, cell_out_ch]
cell_out_ch:2b*( x + y + num_classes +Lx + Ly + p)
"""
super(pln, self).__init__()
self.device = torch.device('cuda')
self.s = s
self.b = b
self.num_classes = num_classes
cell_out_ch = 2 + num_classes +2*s+1
weights = Inception_V3_Weights.IMAGENET1K_V1 # 使用 ImageNet 预训练权重
self.inception = models.inception_v3(weights=weights, aux_logits=True) # 先加载默认结构
# **手动移除辅助分类头**
self.inception.AuxLogits = None
self.inception.aux_logits = False # 显式关闭 aux_logits
# **冻结 InceptionV3 所有参数**
for param in self.inception.parameters():
param.requires_grad = False
self.inception.fc = nn.Identity()
self.inception.avgpool = nn.AdaptiveAvgPool2d((13, 13))
#公用卷积层
self.com_conv1 = nn.Sequential(
nn.Conv2d(2048, 1536, kernel_size=1),
nn.Conv2d(1536, 1536, kernel_size=3, padding=1),
nn.Conv2d(1536, 1536, kernel_size=3, padding=1)
)
# 四个分支的卷积层
self.branch_conv = nn.ModuleList([
nn.Sequential(
nn.Conv2d(1536, 1536, kernel_size=3, padding=1),
nn.Conv2d(1536, 196, kernel_size=3, padding=1),
nn.Conv2d(196, 196, kernel_size=3, padding=2, dilation=2),
nn.Conv2d(196, 196, kernel_size=3, padding=2, dilation=2),
nn.Conv2d(196, 196, kernel_size=3, padding=4, dilation=4),
nn.Conv2d(196, 196, kernel_size=3, padding=8, dilation=8),
nn.Conv2d(196, 196, kernel_size=3, padding=16, dilation=16),
nn.Conv2d(196, 196, kernel_size=3, padding=1),
nn.Conv2d(196, 196, kernel_size=3, padding=1)
) for _ in range(2*b)
])
def forward(self, x):
batch_size = x.size(0)
#print(f'before inception{x.shape}')
x = self.inception(x)
#print(f'after inception{x.shape}')
x = x.view(x.size(0), -1, self.s, self.s)
#print(f'after shape{x.shape}')
x = self.com_conv1(x)
#print(f'after com_conv1{x.shape}')
branch_outputs = []
for branch in self.branch_conv:
output = branch(x)
#print(f'branch {output.shape}')
output = output.view(batch_size, self.s ** 2, -1)
#print(f'branch after view {output.shape}')
branch_outputs.append(output)
# 拼接四个分支的输出
combined_output = torch.cat(branch_outputs, dim=1)
#print(f'combined_output {combined_output.shape}')
# 调整形状为 [batch_size, 4, 13, 13, 204]
final_output = combined_output.view(batch_size, 4, self.s, self.s, 196)
#print(f'final_output{final_output.shape}')
return final_output
class pln_loss:
def __init__(self,s, b, image_size, num_classes):
self.device = torch.device('cuda')
self.s = s
self.b = b
self.image_size = image_size
self.num_classes = num_classes
self.batch_size = 0
def __call__(self, input, target):
"""
:param input: (pln net output)
tensor[4][s, s, 2b*49] bbox: 2b * ( x:0-1grid_cel + y+Lx:s + Ly:s + + + p + )
:param target: (dataset) tensor[n_bbox] bbox: x_min, ymin, xmax, ymax, class
:return: loss tensor
grid type: [[bbox, ..], [], ..] -> bbox_in_grid: c_x(%), c_y(%), w(%), h(%), class(int)
target to grid type
if s = 13 -> grid idx: 13 -> 169
"""
self.batch_size = input.size(0)
#[batchsize][4][s**2][4*49]
target = [self.label_direct2grid(target[i]) for i in range(self.batch_size)]
loss = torch.zeros([self.batch_size, 4], dtype=torch.float, device=self.device)
xy_loss = torch.zeros_like(loss)
link_loss = torch.zeros_like(loss)
conf_loss = torch.zeros_like(loss)
class_loss = torch.zeros_like(loss)
for i in range(self.batch_size):
for j in range(4):
loss[i, j],conf_loss,class_loss[i, j], xy_loss[i, j], link_loss[i, j] = \
self.compute_loss(input[i][j], target[i][j])
return torch.mean(loss), torch.mean(conf_loss), torch.mean(class_loss), torch.mean(xy_loss), torch.mean(link_loss)
def label_direct2grid(self, label):
"""
:param label: dataset type: xmin, ymin, xmax, ymax, class
:return: label: grid type, 包含n_bbox个元素,每个元素有4种点对表示,每个点有51个信息
"""
# 计算每个网格的大小
size = self.image_size // self.s # h, w
# 获取边界框的数量
n_bbox = label.size(0)
# 计算每个单元格输出的通道数
cell_out_ch = 2 + self.num_classes + self.s + self.s + 1
# 初始化各个点的张量
left_top, center_0, right_top, center_1, left_bot, center_2, right_bot, center_3 = \
torch.zeros([n_bbox, cell_out_ch]), torch.zeros([n_bbox, cell_out_ch]), \
torch.zeros([n_bbox, cell_out_ch]), torch.zeros([n_bbox, cell_out_ch]), \
torch.zeros([n_bbox, cell_out_ch]), torch.zeros([n_bbox, cell_out_ch]), \
torch.zeros([n_bbox, cell_out_ch]), torch.zeros([n_bbox, cell_out_ch])
# 计算中心点和四个角点所在的网格索引
# 计算中心点和四个角点所在的网格索引
id_x_center = torch.clamp(((label[:, 0] + label[:, 2]) / 2 // size).int(), 0, self.s - 1)
id_y_center = torch.clamp(((label[:, 1] + label[:, 3]) / 2 // size).int(), 0, self.s - 1)
id_x_lt = torch.clamp((label[:, 0] // size).int(), 0, self.s - 1)
id_y_lt = torch.clamp((label[:, 1] // size).int(), 0, self.s - 1)
id_x_rt = torch.clamp((label[:, 2] // size).int(), 0, self.s - 1)
id_y_rt = torch.clamp((label[:, 1] // size).int(), 0, self.s - 1)
id_x_lb = torch.clamp((label[:, 0] // size).int(), 0, self.s - 1)
id_y_lb = torch.clamp((label[:, 3] // size).int(), 0, self.s - 1)
id_x_rb = torch.clamp((label[:, 2] // size).int(), 0, self.s - 1)
id_y_rb = torch.clamp((label[:, 3] // size).int(), 0, self.s - 1)
# 处理每个边界框
for i in range(n_bbox):
class_id = int(label[i][4])
# 设置 lx, ly
for tensor in [left_top, right_top, left_bot, right_bot]:
tensor[i][2 + self.num_classes + id_x_center[i]] = 1
tensor[i][2 + self.num_classes + self.s + id_y_center[i]] = 1
for tensor, id_x, id_y in zip([center_0, center_1, center_2, center_3],
[id_x_lt, id_x_rt, id_x_lb, id_x_rb],
[id_y_lt, id_y_rt, id_y_lb, id_y_rb]):
tensor[i][2 + self.num_classes + id_x] = 1
tensor[i][2 + self.num_classes + self.s + id_y] = 1
#设置p
for tensor in [left_top, center_0, right_top, center_1, left_bot, center_2, right_bot, center_3]:
tensor[i][-1]=1
# 设置类别标签
for tensor in [left_top, center_0, right_top, center_1, left_bot, center_2, right_bot, center_3]:
tensor[i][2 + class_id] = 1
# 设置网格内的 x, y 坐标
center_x = ((label[i, 0] + label[i, 2]) / 2 % size) / size
center_y = ((label[i, 1] + label[i, 3]) / 2 % size) / size
for tensor in [center_1, center_2, center_3]:
tensor[i][0] = center_x
tensor[i][1] = center_y
left_top[i][0] = (label[i, 0] % size) / size
left_top[i][1] = (label[i, 1] % size) / size
left_bot[i][0] = (label[i, 0] % size) / size
left_bot[i][1] = (label[i, 3] % size) / size
right_top[i][0] = (label[i, 2] % size) / size
right_top[i][1] = (label[i, 1] % size) / size
right_bot[i][0] = (label[i, 2] % size) / size
right_bot[i][1] = (label[i, 3] % size) / size
# 定义点和输出的对应关系
points = [(center_0, left_top, id_x_center, id_y_center, id_x_lt, id_y_lt),
(center_1, right_top, id_x_center, id_y_center, id_x_rt, id_y_rt),
(center_2, left_bot, id_x_center, id_y_center, id_x_lb, id_y_lb),
(center_3, right_bot, id_x_center, id_y_center, id_x_rb, id_y_rb)]
# 把处理后的点放入输出网格
all_outputs = []
for j in range(4):
output = [torch.zeros(4, cell_out_ch) for _ in range(self.s ** 2)]
center_tensor, corner_tensor, id_x_c, id_y_c, id_x_corner, id_y_corner = points[j]
for i in range(n_bbox):
idxc = id_y_c[i]* self.s + id_x_c[i]
idx_corner = id_y_corner[i]* self.s +id_x_corner[i]
#print(f'id_y_c[i] {id_y_c[i]},id_x_c[i] {id_x_c[i] },id_y_corner[i] {id_y_corner[i]}, id_x_corner[i] {id_x_corner[i] }')
#print(f"idxc: {idxc}, idx_corner: {idx_corner}") # 添加打印语句
center_tensor_i = torch.unsqueeze(center_tensor[i], dim=0)
corner_tensor_i = torch.unsqueeze(corner_tensor[i], dim=0)
# 检查前两个维度是否为空
if torch.all(output[idxc][0, :] == 0) and torch.all(output[idx_corner][2, :] == 0):
output[idxc][0] = center_tensor_i
output[idx_corner][2] = corner_tensor_i
continue
# 检查后两个维度是否为空
elif torch.all(output[idx_corner][1,:] == 0) and torch.all(output[idx_corner][3,:] == 0):
output[idxc][1] = center_tensor_i
output[idx_corner][3] = corner_tensor_i
else:
# 若都被占满,则忽略
continue
all_outputs.append(output)
all_outputs = torch.stack([torch.stack(output) for output in all_outputs])
#print(all_outputs.shape)
return all_outputs
def compute_loss(self, input, target):
input = input.to(self.device)
target = target.to(self.device)
w_class = 3
w_coord = 30
w_link = 3
input = input.reshape(self.s ** 2, 2 * self.b, 49)
target = target.reshape(self.s ** 2, 2 * self.b, 49)
# 提取输入的各个部分
input_bbox = input[:, :, :2] # 提取坐标信息
input_class = input[:, :, 2:2 + self.num_classes] # 提取类别相关信息
input_link_x = input[:, :, 22:35] # 提取连接向量 L_x 相关信息
input_link_y = input[:, :, 35:48] # 提取连接向量 L_y 相关信息
input_conf = input[:, :, 48] # 提取点的存在置信度信息
input_bbox = torch.sigmoid(input_bbox)
input_conf = torch.sigmoid(input_conf)
loss = torch.zeros([self.s ** 2], dtype=torch.float, device=self.device)
xy_loss = torch.zeros_like(loss)
conf_loss = torch.zeros_like(loss)
class_loss = torch.zeros_like(loss)
link_loss = torch.zeros_like(loss)
for i in range(self.s ** 2):
l = torch.zeros([4], dtype=torch.float, device=self.device)
target_i = target[i]
target_bbox = target_i[:, :2]
target_class = target_i[:, 2:2 + self.num_classes]
target_link_x = target_i[:, 22:35]
target_link_y = target_i[:, 35:48]
target_conf = target_i[:, 48]
if target_conf.sum() == 0: # 无目标情况
# 置信度损失
l[0] = torch.sum(torch.mul(0.5, torch.pow(input_conf[i] - target_conf, 2)))
else:
l[0] = torch.sum(torch.pow(input_conf[i] - target_conf, 2))
# 分类损失
l[1] = torch.mul(w_class, torch.sum(torch.pow(input_class[i] - target_class, 2)))
# 坐标损失
l[2] = torch.mul(w_coord, torch.sum(torch.pow(input_bbox[i, :, 0] - target_bbox[:, 0], 2) +
torch.pow(input_bbox[i, :, 1] - target_bbox[:, 1], 2)))
# 连接向量损失
l[3] = torch.mul(w_link, torch.sum(torch.pow(input_link_x[i] - target_link_x, 2) +
torch.pow(input_link_y[i] - target_link_y, 2)))
loss[i] = torch.sum(l)
conf_loss[i] = l[0]
class_loss[i] = l[1]
xy_loss[i] = l[2]
link_loss[i] = l[3]
return torch.sum(loss), torch.sum(conf_loss), torch.sum(class_loss), torch.sum(xy_loss), torch.sum(link_loss)
def get_iou(bbox1, bbox2):
"""
计算两个边界框的交并比 (IOU)
:param bbox1: [N, 4],其中每一行是 [xmin, ymin, xmax, ymax]
:param bbox2: [M, 4],其中每一行是 [xmin, ymin, xmax, ymax]
:return: IOU 矩阵 [N, M]
"""
# 计算交集的坐标
xmin = torch.maximum(bbox1[:, 0].unsqueeze(1), bbox2[:, 0].unsqueeze(0))
ymin = torch.maximum(bbox1[:, 1].unsqueeze(1), bbox2[:, 1].unsqueeze(0))
xmax = torch.minimum(bbox1[:, 2].unsqueeze(1), bbox2[:, 2].unsqueeze(0))
ymax = torch.minimum(bbox1[:, 3].unsqueeze(1), bbox2[:, 3].unsqueeze(0))
# 计算交集的面积
intersection = torch.clamp(xmax - xmin, min=0) * torch.clamp(ymax - ymin, min=0)
# 计算两个边界框的面积
area1 = (bbox1[:, 2] - bbox1[:, 0]) * (bbox1[:, 3] - bbox1[:, 1])
area2 = (bbox2[:, 2] - bbox2[:, 0]) * (bbox2[:, 3] - bbox2[:, 1])
# 计算并集的面积
union = area1.unsqueeze(1) + area2.unsqueeze(0) - intersection
# 计算 IOU
iou = intersection / union
return iou
def nms(bboxes, conf_th, iou_th):
"""
非极大值抑制 (NMS)
:param bboxes: [N, 6],其中每一行是 [xmin, ymin, xmax, ymax, obj_conf, classes]
:param conf_th: 置信度阈值
:param iou_th: IOU 阈值
:return: 过滤后的边界框
"""
# 过滤掉置信度低于阈值的边界框
bboxes = bboxes[bboxes[:, 4] > conf_th]
# 按置信度排序
indices = torch.argsort(bboxes[:, 4], descending=True)
bboxes = bboxes[indices]
keep = []
while bboxes.size(0) > 0:
# 选择置信度最高的边界框
keep.append(bboxes[0])
ious = get_iou(bboxes[0].unsqueeze(0)[:, :4], bboxes[1:, :4])
# 过滤掉与当前边界框 IOU 大于阈值的边界框
bboxes = bboxes[1:][ious < iou_th]
return torch.stack(keep)
def output_process(output, image_size, s, b, conf_th, iou_th):
"""
param: output [batch_size, 4, 13, 13, 196]
:return output: list[], bbox: xmin, ymin, xmax, ymax, obj_conf, classes_conf, classes
"""
batch_size = output.size(0)
grid_size = s
num_classes = 20 # 假设类别数为 20
# 将输出转换为 [batch_size, 4, s^2, 4, 49] 的形状
output = output.view(batch_size, 4, grid_size ** 2, 4, 49)
# 提取每个点的置信度、类别、位置和链接信息
point_conf = output[:, :, :, :, 48] # 点存在概率
classes_conf = output[:, :, :, :, 2:2 + num_classes] # 类别置信度
x = output[:, :, :, :, 0] # x 偏移量
y = output[:, :, :, :, 1] # y 偏移量
link_x = output[:, :, :, :, 22:35] # 链接向量 Lx
link_y = output[:, :, :, :, 35:48] # 链接向量 Ly
bboxes = []
for i in range(batch_size):
for branch in range(4): # 遍历 4 个分支
for grid_idx in range(grid_size ** 2): # 遍历每个网格
for point_idx in range(4): # 遍历每个点
# 提取当前点的信息
point_x = x[i, branch, grid_idx, point_idx]
point_y = y[i, branch, grid_idx, point_idx]
point_confidence = point_conf[i, branch, grid_idx, point_idx]
if point_idx < 2: # 前两个点为 center
center_x = (grid_idx % grid_size + point_x) * (image_size / grid_size)
center_y = (grid_idx // grid_size + point_y) * (image_size / grid_size)
else: # 后两个点为 corner
corner_x = (grid_idx % grid_size + point_x) * (image_size / grid_size)
corner_y = (grid_idx // grid_size + point_y) * (image_size / grid_size)
for classes in range(num_classes):
point_class_conf = classes_conf[i, branch, grid_idx, point_idx,classes]
for grid_idx_pair in range(grid_size ** 2):
if point_idx < 2: # 前两个点为 center
point_idx_pair = point_idx +2
point_x_pair = x[i, branch, grid_idx_pair, point_idx_pair]
point_y_pair = y[i, branch, grid_idx_pair, point_idx_pair]
corner_x = (grid_idx_pair % grid_size + point_x_pair) * (image_size / grid_size)
corner_y = (grid_idx_pair // grid_size + point_y_pair) * (image_size / grid_size)
else: # 后两个点为 corner
point_idx_pair = point_idx-2
point_x_pair = x[i, branch, grid_idx_pair, point_idx_pair]
point_y_pair = y[i, branch, grid_idx_pair, point_idx_pair]
center_x = (grid_idx_pair % grid_size + point_x_pair) * (image_size / grid_size)
center_y = (grid_idx_pair // grid_size + point_y_pair) * (image_size / grid_size)
point_confidence_pair = point_conf[i, branch, grid_idx_pair, point_idx_pair]
point_class_conf_pair = classes_conf[i, branch, grid_idx_pair, point_idx_pair,classes]
L_x = link_x[i, branch,grid_idx,point_idx,grid_idx_pair % grid_size]
L_y = link_y[i, branch,grid_idx,point_idx,grid_idx_pair // grid_size]
L_x_pair = link_x[i, branch,grid_idx,point_idx,grid_idx % grid_size]
L_y_pair = link_y[i, branch,grid_idx,point_idx,grid_idx // grid_size]
obj_conf = point_confidence*point_confidence_pair*point_class_conf*point_class_conf_pair*((L_x*L_y+L_x_pair*L_y_pair)/2)
half_w = abs(corner_x-center_x)
half_h = abs(corner_y-center_y)
x_min = center_x - half_w
y_min = center_y - half_h
x_max = center_x + half_w
y_max = center_y + half_h
bboxes.append([x_min, y_min, x_max, y_max, obj_conf, classes])
# 将边界框列表转换为张量
bboxes = torch.tensor(bboxes)
# 应用 NMS
filtered_bboxes = nms(bboxes, conf_th, iou_th)
return filtered_bboxes
if __name__ == "__main__":
import torch
# Test pln
x = torch.randn([1, 3, 448, 448])
s = 13
b = 2
net = pln(s, b,20)
#print(net)
# out = net(x)
# print(out)
# print(out.size())
# Test PLN_loss
# 测试时假设 s=13, class=2
image_size = 448
input = torch.randn([2, 4, s ** 2, 2 * b * 49])
input = input
target = [torch.tensor([[100, 300, 200,400, 2],
[105, 305, 205,405, 3],
[300, 300, 400, 400, 5]], dtype=torch.float) for _ in range(2)]
criterion = pln_loss( s, b, image_size, 20)
loss = criterion(input, target)
print(loss)