金安合肥网站建设专业,百度咨询,wordpress 增加icon,wordpress里买的模板可以改13.2 微调
为了防止在训练集上过拟合#xff0c;有两种办法#xff0c;第一种是扩大训练集数量#xff0c;但是需要大量的成本#xff1b;第二种就是应用迁移学习#xff0c;将源数据学习到的知识迁移到目标数据集#xff0c;即在把在源数据训练好的参数和模型#xff…13.2 微调
为了防止在训练集上过拟合有两种办法第一种是扩大训练集数量但是需要大量的成本第二种就是应用迁移学习将源数据学习到的知识迁移到目标数据集即在把在源数据训练好的参数和模型除去输出层直接复制到目标数据集训练。
# IPython魔法函数可以不用执行plt .show()
%matplotlib inline
import os
import torch
import torchvision
from torch import nn
from d2l import torch as d2l
13.2.1 获取数据集
#save
d2l.DATA_HUB[hotdog] (d2l.DATA_URL hotdog.zip,fba480ffa8aa7e0febbb511d181409f899b9baa5)data_dir d2l.download_extract(hotdog)
train_imgs torchvision.datasets.ImageFolder(os.path.join(data_dir, train))
test_imgs torchvision.datasets.ImageFolder(os.path.join(data_dir, test))
hotdogs [train_imgs[i][0] for i in range(8)]
not_hotdogs [train_imgs[-i-1][0] for i in range(8)]
# 展示2行8列矩阵的图片共16张
d2l.show_images(hotdogsnot_hotdogs,2,8,scale1.5)
# 使用RGB通道的均值和标准差以标准化每个通道
normalize torchvision.transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
# 图像增广
train_augs torchvision.transforms.Compose([torchvision.transforms.RandomResizedCrop(224),torchvision.transforms.RandomHorizontalFlip(),torchvision.transforms.ToTensor(),normalize])
test_augs torchvision.transforms.Compose([torchvision.transforms.Resize([256, 256]),torchvision.transforms.CenterCrop(224),torchvision.transforms.ToTensor(),normalize]) 13.2.2 初始化模型
# 自动下载网上的训练模型
finetune_net torchvision.models.resnet18(pretrainedTrue)
# 输入张量的形状还是源输入张量大小输入张量大小改为2
finetune_net.fc nn.Linear(finetune_net.fc.in_features, 2)
nn.init.xavier_uniform_(finetune_net.fc.weight);
13.2.3 微调模型
# 如果param_groupTrue输出层中的模型参数将使用十倍的学习率
# 如果param_groupFalse输出层中模型参数为随机值
# 训练模型
def train_fine_tuning(net, learning_rate, batch_size128, num_epochs5,param_groupTrue):train_iter torch.utils.data.DataLoader(torchvision.datasets.ImageFolder(os.path.join(data_dir, train), transformtrain_augs),batch_sizebatch_size, shuffleTrue)test_iter torch.utils.data.DataLoader(torchvision.datasets.ImageFolder(os.path.join(data_dir, test), transformtest_augs),batch_sizebatch_size)devices d2l.try_all_gpus()loss nn.CrossEntropyLoss(reductionnone)if param_group:params_1x [param for name, param in net.named_parameters()if name not in [fc.weight, fc.bias]]# params_1x的参数使用learning_rate学习率 net.fc.parameters()的参数使用0.001的学习率trainer torch.optim.SGD([{params: params_1x},{params: net.fc.parameters(),lr: learning_rate * 10}],lrlearning_rate, weight_decay0.001)else:trainer torch.optim.SGD(net.parameters(), lrlearning_rate,weight_decay0.001)d2l.train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs,devices)
train_fine_tuning(finetune_net, 5e-5)
13.3 目标检测和边界框
有时候不仅要识别图像的类别还需要识别图像的位置。在计算机视觉中叫做目标识别或者目标检测。这小节是介绍目标检测的深度学习方法。
%matplotlib inline
import torch
from d2l import torch as d2l
#save
def box_corner_to_center(boxes):从左上右下转换到中间宽度高度x1, y1, x2, y2 boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]# cx,xy,w,h的维度是ncx (x1 x2) / 2cy (y1 y2) / 2w x2 - x1h y2 - y1# torch.stack()沿着新维度对张量进行链接。boxes最开始维度是n4axis-1表示倒数第一个维度# torch.stack()将(cx, cy, w, h)的维度n将其沿着倒数第一个维度拼接在一起又是n4boxes torch.stack((cx, cy, w, h), axis-1)return boxes#save
def box_center_to_corner(boxes):从中间宽度高度转换到左上右下cx, cy, w, h boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]x1 cx - 0.5 * wy1 cy - 0.5 * hx2 cx 0.5 * wy2 cy 0.5 * hboxes torch.stack((x1, y1, x2, y2), axis-1)return boxes
13.4 锚框
目标检测算法通常会在图像中采集大量的样本本小节介绍其中一个采样办法以某个像素为中心生成多个不同缩放比和宽高比的边界框。
13.4.1 生成多个锚框
%matplotlib inline
import torch
from d2l import torch as d2ltorch.set_printoptions(2) # 精简输出精度显示小数点后2位形成多个锚框
params:data图像(批量大小通道数高宽)sizes缩放比尺寸集合ratios宽高比集合
def multibox_prior(data, sizes, ratios):# 获取data后两位的值也就是图像的高和宽in_height, in_width data.shape[-2:] params:devicecpu或者gpunum_sizes尺寸的个数nnum_ratios宽高比个数mdevice, num_sizes, num_ratios data.device, len(sizes), len(ratios)# 以同一像素为中心的锚框数量nm-1boxes_per_pixel (num_sizes num_ratios - 1)size_tensor torch.tensor(sizes, devicedevice)ratio_tensor torch.tensor(ratios, devicedevice)# offset为了将锚点移动到像素的中心需要设置偏移量。# steps归一化将宽高规化到0-1之间因为一个像素的高为1且宽为1我们选择偏移我们的中心0.5offset_h, offset_w 0.5, 0.5steps_h 1.0 / in_height # 在y轴上缩放步长steps_w 1.0 / in_width # 在x轴上缩放步长# 假设宽高512*216 那么torch.arange(in_height, devicedevice)【012...511】,移动到中心就是[0.5,1.5...511.5]# 第一步torch.arange(in_height, devicedevice) offset_h代表移动到每个像素的中心因为每个像素1*1大小.# 第二步宽高进行归一化center_h (torch.arange(in_height, devicedevice) offset_h) * steps_hcenter_w (torch.arange(in_width, devicedevice) offset_w) * steps_wa torch.tensor([1, 2, 3, 4])b torch.tensor([4, 5, 6])x, y torch.meshgrid(a, b,indexingij)print:tensor([[1, 1, 1],[2, 2, 2],[3, 3, 3],[4, 4, 4]])tensor([[4, 5, 6],[4, 5, 6],[4, 5, 6],[4, 5, 6]])x, y torch.meshgrid(a, b,indexingxy)print:tensor([[1, 2, 3, 4],[1, 2, 3, 4],[1, 2, 3, 4]])tensor([[4, 4, 4, 4],[5, 5, 5, 5],[6, 6, 6, 6]])# 对比上面例子假设center_htensor([0.5,1.5...511.5])(实际上是0-1的值这里为了简单理解写成这样) # 则shift_ytensor([0.5,0.5..],[1.5,1.5,...],...[511.5,511.5...])shift_y, shift_x torch.meshgrid(center_h, center_w, indexingij) # 将shift展平成一维序列用上述的例子则shift_y为tensor([0.5,0.5...511.5,511.5])shift_y, shift_x shift_y.reshape(-1), shift_x.reshape(-1)# 宽h*s*sqrt(r)# 由于锚框只考虑s1和r1的组合r1组合就是size_tensor * torch.sqrt(ratio_tensor[0])s1组合就是sizes[0] * torch.sqrt(ratio_tensor[1:])# 此处要乘上in_height / in_width是因为假设此时ratios宽高比为1那么默认wh但是实际上ratios代表与原图宽高比一致举个例子# 假设原图1000*10那么当ratios为1时此时wh而我们需要的是w/h 1000/10所以需要乘上in_height / in_width来与原尺寸保持一致w torch.cat((size_tensor * torch.sqrt(ratio_tensor[0]),sizes[0] * torch.sqrt(ratio_tensor[1:])))\* in_height / in_width # 处理矩形输入h torch.cat((size_tensor / torch.sqrt(ratio_tensor[0]),sizes[0] / torch.sqrt(ratio_tensor[1:])))# 除以2来获得半高和半宽# 每一行(-w, -h, w, h)对应一个锚框一个锚框的左上角偏差和右下角偏差anchor_manipulations torch.stack((-w, -h, w, h)).T.repeat(in_height * in_width, 1) / 2# 每个中心点都将有boxes_per_pixel(nm-1)个锚框# 形状w*h*(nm-1) 4out_grid torch.stack([shift_x, shift_y, shift_x, shift_y],dim1).repeat_interleave(boxes_per_pixel, dim0)output out_grid anchor_manipulations# 添加一个维度return output.unsqueeze(0)img d2l.plt.imread(../data/img/catdog.jpg)
h, w img.shape[:2] # (1080, 1920)
X torch.rand(size(1, 3, h, w))
Y multibox_prior(X, sizes[0.75, 0.5, 0.25], ratios[1, 2, 0.5])
print(Y.shape)
# 即将Y变成高宽以同一像素点为中心的锚框数4
# 每个锚框有四个元素锚框的左上角xy坐标和锚框右下角的xy坐标
# nm-133-15
boxes Y.reshape(h, w, 5, 4)
# 访问以250250为中心的第一个锚框
boxes[250, 250, 0, :]
# 显示以某个像素点为中心的所有锚框params:axes:图像坐标bboxes某个像素点中心坐标labels显示文本例如s0.2,r1colors锚框的颜色def show_bboxes(axes, bboxes, labelsNone, colorsNone):显示所有边界框def _make_list(obj, default_valuesNone):if obj is None:obj default_valueselif not isinstance(obj, (list, tuple)):obj [obj]return objlabels _make_list(labels)colors _make_list(colors, [b, g, r, m, c])for i, bbox in enumerate(bboxes):color colors[i % len(colors)]# bbox_to_rect将边界框(左上x,左上y,右下x,右下y)格式转换成matplotlib格式# ((左上x,左上y),宽,高)rect d2l.bbox_to_rect(bbox.detach().numpy(), color)axes.add_patch(rect)if labels and len(labels) i:text_color k if color w else waxes.text(rect.xy[0], rect.xy[1], labels[i],vacenter, hacenter, fontsize9, colortext_color,bboxdict(facecolorcolor, lw0))
d2l.set_figsize()
bbox_scale torch.tensor((w, h, w, h))
fig d2l.plt.imshow(img)
show_bboxes(fig.axes, boxes[750, 750, :, :] * bbox_scale,[s0.75, r1, s0.5, r1, s0.25, r1, s0.75, r2,s0.75, r0.5])
13.4.2 交并比
# 衡量锚框与真实框之间或者锚框与锚框之间的相似度即A∩B/A∪B
def box_iou(boxes1, boxes2):计算两个锚框或边界框列表中成对的交并比box_area lambda boxes: ((boxes[:, 2] - boxes[:, 0]) *(boxes[:, 3] - boxes[:, 1]))# boxes1,boxes2,areas1,areas2的形状:# boxes1(boxes1的数量,4),# boxes2(boxes2的数量,4),# areas1(boxes1的数量,),# areas2(boxes2的数量,)areas1 box_area(boxes1)areas2 box_area(boxes2)# inter_upperlefts,inter_lowerrights,inters的形状:# (boxes1的数量,boxes2的数量,2)inter_upperlefts torch.max(boxes1[:, None, :2], boxes2[:, :2])inter_lowerrights torch.min(boxes1[:, None, 2:], boxes2[:, 2:])inters (inter_lowerrights - inter_upperlefts).clamp(min0)# inter_areasandunion_areas的形状:(boxes1的数量,boxes2的数量)inter_areas inters[:, :, 0] * inters[:, :, 1]union_areas areas1[:, None] areas2 - inter_areasreturn inter_areas / union_areas
13.4.3 在训练数据中标注锚框
%matplotlib inline
import torch
from d2l import torch as d2ltorch.set_printoptions(2) # 精简输出精度显示小数点后2位形成多个锚框
params:data图像(批量大小通道数高宽)sizes缩放比尺寸集合ratios宽高比集合
def multibox_prior(data, sizes, ratios):# 获取data后两位的值也就是图像的高和宽in_height, in_width data.shape[-2:] params:devicecpu或者gpunum_sizes尺寸的个数nnum_ratios宽高比个数mdevice, num_sizes, num_ratios data.device, len(sizes), len(ratios)# 以同一像素为中心的锚框数量nm-1boxes_per_pixel (num_sizes num_ratios - 1)size_tensor torch.tensor(sizes, devicedevice)ratio_tensor torch.tensor(ratios, devicedevice)# offset为了将锚点移动到像素的中心需要设置偏移量。# steps归一化将宽高规化到0-1之间因为一个像素的高为1且宽为1我们选择偏移我们的中心0.5offset_h, offset_w 0.5, 0.5steps_h 1.0 / in_height # 在y轴上缩放步长steps_w 1.0 / in_width # 在x轴上缩放步长# 假设宽高512*216 那么torch.arange(in_height, devicedevice)【012...511】,移动到中心就是[0.5,1.5...511.5]# 第一步torch.arange(in_height, devicedevice) offset_h代表移动到每个像素的中心因为每个像素1*1大小.# 第二步宽高进行归一化center_h (torch.arange(in_height, devicedevice) offset_h) * steps_hcenter_w (torch.arange(in_width, devicedevice) offset_w) * steps_wa torch.tensor([1, 2, 3, 4])b torch.tensor([4, 5, 6])x, y torch.meshgrid(a, b,indexingij)print:tensor([[1, 1, 1],[2, 2, 2],[3, 3, 3],[4, 4, 4]])tensor([[4, 5, 6],[4, 5, 6],[4, 5, 6],[4, 5, 6]])x, y torch.meshgrid(a, b,indexingxy)print:tensor([[1, 2, 3, 4],[1, 2, 3, 4],[1, 2, 3, 4]])tensor([[4, 4, 4, 4],[5, 5, 5, 5],[6, 6, 6, 6]])# 对比上面例子假设center_htensor([0.5,1.5...511.5])(实际上是0-1的值这里为了简单理解写成这样) # 则shift_ytensor([0.5,0.5..],[1.5,1.5,...],...[511.5,511.5...])shift_y, shift_x torch.meshgrid(center_h, center_w, indexingij) # 将shift展平成一维序列用上述的例子则shift_y为tensor([0.5,0.5...511.5,511.5])shift_y, shift_x shift_y.reshape(-1), shift_x.reshape(-1)# 宽h*s*sqrt(r)# 由于锚框只考虑s1和r1的组合r1组合就是size_tensor * torch.sqrt(ratio_tensor[0])s1组合就是sizes[0] * torch.sqrt(ratio_tensor[1:])# 此处要乘上in_height / in_width是因为假设此时ratios宽高比为1那么默认wh但是实际上ratios代表与原图宽高比一致举个例子# 假设原图1000*10那么当ratios为1时此时wh而我们需要的是w/h 1000/10所以需要乘上in_height / in_width来与原尺寸保持一致w torch.cat((size_tensor * torch.sqrt(ratio_tensor[0]),sizes[0] * torch.sqrt(ratio_tensor[1:])))\* in_height / in_width # 处理矩形输入h torch.cat((size_tensor / torch.sqrt(ratio_tensor[0]),sizes[0] / torch.sqrt(ratio_tensor[1:])))# 除以2来获得半高和半宽# 每一行(-w, -h, w, h)对应一个锚框一个锚框的左上角偏差和右下角偏差anchor_manipulations torch.stack((-w, -h, w, h)).T.repeat(in_height * in_width, 1) / 2# 每个中心点都将有boxes_per_pixel(nm-1)个锚框# 形状w*h*(nm-1) 4out_grid torch.stack([shift_x, shift_y, shift_x, shift_y],dim1).repeat_interleave(boxes_per_pixel, dim0)output out_grid anchor_manipulations# 添加一个维度return output.unsqueeze(0)img d2l.plt.imread(../data/img/catdog.jpg)
h, w img.shape[:2] # (1080, 1920)
X torch.rand(size(1, 3, h, w))
Y multibox_prior(X, sizes[0.75, 0.5, 0.25], ratios[1, 2, 0.5])
print(Y.shape)
# 即将Y变成高宽以同一像素点为中心的锚框数4
# 每个锚框有四个元素锚框的左上角xy坐标和锚框右下角的xy坐标
# nm-133-15
boxes Y.reshape(h, w, 5, 4)
# 访问以250250为中心的第一个锚框
boxes[250, 250, 0, :]
# 显示以某个像素点为中心的所有锚框params:axes:图像坐标bboxes某个像素点中心坐标labels显示文本例如s0.2,r1colors锚框的颜色def show_bboxes(axes, bboxes, labelsNone, colorsNone):显示所有边界框def _make_list(obj, default_valuesNone):if obj is None:obj default_valueselif not isinstance(obj, (list, tuple)):obj [obj]return objlabels _make_list(labels)colors _make_list(colors, [b, g, r, m, c])for i, bbox in enumerate(bboxes):color colors[i % len(colors)]# bbox_to_rect将边界框(左上x,左上y,右下x,右下y)格式转换成matplotlib格式# ((左上x,左上y),宽,高)rect d2l.bbox_to_rect(bbox.detach().numpy(), color)axes.add_patch(rect)if labels and len(labels) i:text_color k if color w else waxes.text(rect.xy[0], rect.xy[1], labels[i],vacenter, hacenter, fontsize9, colortext_color,bboxdict(facecolorcolor, lw0))
d2l.set_figsize()
bbox_scale torch.tensor((w, h, w, h))
fig d2l.plt.imshow(img)
show_bboxes(fig.axes, boxes[750, 750, :, :] * bbox_scale,[s0.75, r1, s0.5, r1, s0.25, r1, s0.75, r2,s0.75, r0.5])
# 衡量锚框与真实框之间或者锚框与锚框之间的相似度即A∩B/A∪B
def box_iou(boxes1, boxes2):计算两个锚框或边界框列表中成对的交并比box_area lambda boxes: ((boxes[:, 2] - boxes[:, 0]) *(boxes[:, 3] - boxes[:, 1]))# boxes1,boxes2,areas1,areas2的形状:# boxes1(boxes1的数量,4),# boxes2(boxes2的数量,4),# areas1(boxes1的数量,),# areas2(boxes2的数量,)areas1 box_area(boxes1)areas2 box_area(boxes2)# inter_upperlefts,inter_lowerrights,inters的形状:# (boxes1的数量,boxes2的数量,2)inter_upperlefts torch.max(boxes1[:, None, :2], boxes2[:, :2])inter_lowerrights torch.min(boxes1[:, None, 2:], boxes2[:, 2:])inters (inter_lowerrights - inter_upperlefts).clamp(min0)# inter_areasandunion_areas的形状:(boxes1的数量,boxes2的数量)inter_areas inters[:, :, 0] * inters[:, :, 1]union_areas areas1[:, None] areas2 - inter_areasreturn inter_areas / union_areas
# 将最接近的真实边界框分配给锚框
# iou_threshold阈值
def assign_anchor_to_bbox(ground_truth, anchors, device, iou_threshold0.5):# num_anchorsna num_gt_boxesnbnum_anchors, num_gt_boxes anchors.shape[0], ground_truth.shape[0]# 位于第i行和第j列的元素x_ij是锚框i和真实边界框j的IoUjaccard box_iou(anchors, ground_truth)# 对于每个锚框分配的真实边界框的张量初始值为-1anchors_bbox_map torch.full((num_anchors,), -1, dtypetorch.long,devicedevice)# 找到每一行中最大交并比的ground_truth和anchors索引号max_ious, indices torch.max(jaccard, dim1)# 找到剩余交并比大于阈值的索引号anc_i torch.nonzero(max_ious iou_threshold).reshape(-1)box_j indices[max_ious iou_threshold]anchors_bbox_map[anc_i] box_j# 删去这些索引行和列col_discard torch.full((num_anchors,), -1)row_discard torch.full((num_gt_boxes,), -1)for _ in range(num_gt_boxes):max_idx torch.argmax(jaccard)box_idx (max_idx % num_gt_boxes).long()anc_idx (max_idx / num_gt_boxes).long()anchors_bbox_map[anc_idx] box_idxjaccard[:, box_idx] col_discardjaccard[anc_idx, :] row_discardreturn anchors_bbox_map
#save
def offset_boxes(anchors, assigned_bb, eps1e-6):对锚框偏移量的转换c_anc d2l.box_corner_to_center(anchors)c_assigned_bb d2l.box_corner_to_center(assigned_bb)offset_xy 10 * (c_assigned_bb[:, :2] - c_anc[:, :2]) / c_anc[:, 2:]offset_wh 5 * torch.log(eps c_assigned_bb[:, 2:] / c_anc[:, 2:])offset torch.cat([offset_xy, offset_wh], axis1)return offset
#save
def multibox_target(anchors, labels):使用真实边界框标记锚框batch_size, anchors labels.shape[0], anchors.squeeze(0)batch_offset, batch_mask, batch_class_labels [], [], []device, num_anchors anchors.device, anchors.shape[0]for i in range(batch_size):label labels[i, :, :]anchors_bbox_map assign_anchor_to_bbox(label[:, 1:], anchors, device)bbox_mask ((anchors_bbox_map 0).float().unsqueeze(-1)).repeat(1, 4)# 将类标签和分配的边界框坐标初始化为零class_labels torch.zeros(num_anchors, dtypetorch.long,devicedevice)assigned_bb torch.zeros((num_anchors, 4), dtypetorch.float32,devicedevice)# 使用真实边界框来标记锚框的类别。# 如果一个锚框没有被分配标记其为背景值为零indices_true torch.nonzero(anchors_bbox_map 0)bb_idx anchors_bbox_map[indices_true]class_labels[indices_true] label[bb_idx, 0].long() 1assigned_bb[indices_true] label[bb_idx, 1:]# 偏移量转换offset offset_boxes(anchors, assigned_bb) * bbox_maskbatch_offset.append(offset.reshape(-1))batch_mask.append(bbox_mask.reshape(-1))batch_class_labels.append(class_labels)bbox_offset torch.stack(batch_offset)bbox_mask torch.stack(batch_mask)class_labels torch.stack(batch_class_labels)return (bbox_offset, bbox_mask, class_labels)ground_truth torch.tensor([[0, 0.1, 0.08, 0.52, 0.92],[1, 0.55, 0.2, 0.9, 0.88]])
anchors torch.tensor([[0, 0.1, 0.2, 0.3], [0.15, 0.2, 0.4, 0.4],[0.63, 0.05, 0.88, 0.98], [0.66, 0.45, 0.8, 0.8],[0.57, 0.3, 0.92, 0.9]])