当前位置: 首页 > news >正文

做羊水亲子鉴定网站免费新闻源发布平台

做羊水亲子鉴定网站,免费新闻源发布平台,自己做装修图网站,建设银行网站账号怎么注销全卷积网络 sec_fcn 如 :numref:sec_semantic_segmentation中所介绍的那样,语义分割是对图像中的每个像素分类。 全卷积网络(fully convolutional network,FCN)采用卷积神经网络实现了从图像像素到像素类别的变换 :cite:Long.Sh…

全卷积网络

sec_fcn

如 :numref:sec_semantic_segmentation中所介绍的那样,语义分割是对图像中的每个像素分类。
全卷积网络(fully convolutional network,FCN)采用卷积神经网络实现了从图像像素到像素类别的变换 :cite:Long.Shelhamer.Darrell.2015
与我们之前在图像分类或目标检测部分介绍的卷积神经网络不同,全卷积网络将中间层特征图的高和宽变换回输入图像的尺寸:这是通过在 :numref:sec_transposed_conv中引入的转置卷积(transposed convolution)实现的。
因此,输出的类别预测与输入图像在像素级别上具有一一对应关系:通道维的输出即该位置对应像素的类别预测。

%matplotlib inline
import torch
import torchvision
from torch import nn
from torch.nn import functional as F
from d2l import torch as d2l

构造模型

下面我们了解一下全卷积网络模型最基本的设计。
如 :numref:fig_fcn所示,全卷积网络先使用卷积神经网络抽取图像特征,然后通过 1 × 1 1\times 1 1×1卷积层将通道数变换为类别个数,最后在 :numref:sec_transposed_conv中通过转置卷积层将特征图的高和宽变换为输入图像的尺寸。
因此,模型输出与输入图像的高和宽相同,且最终输出通道包含了该空间位置像素的类别预测。

在这里插入图片描述

🏷fig_fcn

下面,我们[使用在ImageNet数据集上预训练的ResNet-18模型来提取图像特征],并将该网络记为pretrained_net
ResNet-18模型的最后几层包括全局平均汇聚层和全连接层,然而全卷积网络中不需要它们。

pretrained_net = torchvision.models.resnet18(pretrained=True)
list(pretrained_net.children())[-3:]
Downloading: "https://download.pytorch.org/models/resnet18-f37072fd.pth" to /home/ci/.cache/torch/hub/checkpoints/resnet18-f37072fd.pth0%|          | 0.00/44.7M [00:00<?, ?B/s][Sequential((0): BasicBlock((conv1): Conv2d(256, 512, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)(bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(relu): ReLU(inplace=True)(conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)(bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(downsample): Sequential((0): Conv2d(256, 512, kernel_size=(1, 1), stride=(2, 2), bias=False)(1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)))(1): BasicBlock((conv1): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)(bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(relu): ReLU(inplace=True)(conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)(bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True))),AdaptiveAvgPool2d(output_size=(1, 1)),Linear(in_features=512, out_features=1000, bias=True)]

接下来,我们[创建一个全卷积网络net]。
它复制了ResNet-18中大部分的预训练层,除了最后的全局平均汇聚层和最接近输出的全连接层。

net = nn.Sequential(*list(pretrained_net.children())[:-2])

给定高度为320和宽度为480的输入,net的前向传播将输入的高和宽减小至原来的 1 / 32 1/32 1/32,即10和15。

X = torch.rand(size=(1, 3, 320, 480))
net(X).shape
torch.Size([1, 512, 10, 15])

接下来[使用 1 × 1 1\times1 1×1卷积层将输出通道数转换为Pascal VOC2012数据集的类数(21类)。]
最后需要(将特征图的高度和宽度增加32倍),从而将其变回输入图像的高和宽。
回想一下 :numref:sec_padding中卷积层输出形状的计算方法:
由于 ( 320 − 64 + 16 × 2 + 32 ) / 32 = 10 (320-64+16\times2+32)/32=10 (32064+16×2+32)/32=10 ( 480 − 64 + 16 × 2 + 32 ) / 32 = 15 (480-64+16\times2+32)/32=15 (48064+16×2+32)/32=15,我们构造一个步幅为 32 32 32的转置卷积层,并将卷积核的高和宽设为 64 64 64,填充为 16 16 16
我们可以看到如果步幅为 s s s,填充为 s / 2 s/2 s/2(假设 s / 2 s/2 s/2是整数)且卷积核的高和宽为 2 s 2s 2s,转置卷积核会将输入的高和宽分别放大 s s s倍。

num_classes = 21
net.add_module('final_conv', nn.Conv2d(512, num_classes, kernel_size=1))
net.add_module('transpose_conv', nn.ConvTranspose2d(num_classes, num_classes,kernel_size=64, padding=16, stride=32))

[初始化转置卷积层]

在图像处理中,我们有时需要将图像放大,即上采样(upsampling)。
双线性插值(bilinear interpolation)
是常用的上采样方法之一,它也经常用于初始化转置卷积层。

为了解释双线性插值,假设给定输入图像,我们想要计算上采样输出图像上的每个像素。

  1. 将输出图像的坐标 ( x , y ) (x,y) (x,y)映射到输入图像的坐标 ( x ′ , y ′ ) (x',y') (x,y)上。
    例如,根据输入与输出的尺寸之比来映射。
    请注意,映射后的 x ′ x′ x y ′ y′ y是实数。
  2. 在输入图像上找到离坐标 ( x ′ , y ′ ) (x',y') (x,y)最近的4个像素。
  3. 输出图像在坐标 ( x , y ) (x,y) (x,y)上的像素依据输入图像上这4个像素及其与 ( x ′ , y ′ ) (x',y') (x,y)的相对距离来计算。

双线性插值的上采样可以通过转置卷积层实现,内核由以下bilinear_kernel函数构造。
限于篇幅,我们只给出bilinear_kernel函数的实现,不讨论算法的原理。

def bilinear_kernel(in_channels, out_channels, kernel_size):factor = (kernel_size + 1) // 2if kernel_size % 2 == 1:center = factor - 1else:center = factor - 0.5og = (torch.arange(kernel_size).reshape(-1, 1),torch.arange(kernel_size).reshape(1, -1))filt = (1 - torch.abs(og[0] - center) / factor) * \(1 - torch.abs(og[1] - center) / factor)weight = torch.zeros((in_channels, out_channels,kernel_size, kernel_size))weight[range(in_channels), range(out_channels), :, :] = filtreturn weight

让我们用[双线性插值的上采样实验]它由转置卷积层实现。
我们构造一个将输入的高和宽放大2倍的转置卷积层,并将其卷积核用bilinear_kernel函数初始化。

conv_trans = nn.ConvTranspose2d(3, 3, kernel_size=4, padding=1, stride=2,bias=False)
conv_trans.weight.data.copy_(bilinear_kernel(3, 3, 4));

读取图像X,将上采样的结果记作Y。为了打印图像,我们需要调整通道维的位置。

img = torchvision.transforms.ToTensor()(d2l.Image.open('../img/catdog.jpg'))
X = img.unsqueeze(0)
Y = conv_trans(X)
out_img = Y[0].permute(1, 2, 0).detach()

可以看到,转置卷积层将图像的高和宽分别放大了2倍。
除了坐标刻度不同,双线性插值放大的图像和在 :numref:sec_bbox中打印出的原图看上去没什么两样。

d2l.set_figsize()
print('input image shape:', img.permute(1, 2, 0).shape)
d2l.plt.imshow(img.permute(1, 2, 0));
print('output image shape:', out_img.shape)
d2l.plt.imshow(out_img);
input image shape: torch.Size([561, 728, 3])
output image shape: torch.Size([1122, 1456, 3])

在这里插入图片描述

全卷积网络[用双线性插值的上采样初始化转置卷积层。对于 1 × 1 1\times 1 1×1卷积层,我们使用Xavier初始化参数。]

W = bilinear_kernel(num_classes, num_classes, 64)
net.transpose_conv.weight.data.copy_(W);

[读取数据集]

我们用 :numref:sec_semantic_segmentation中介绍的语义分割读取数据集。
指定随机裁剪的输出图像的形状为 320 × 480 320\times 480 320×480:高和宽都可以被 32 32 32整除。

batch_size, crop_size = 32, (320, 480)
train_iter, test_iter = d2l.load_data_voc(batch_size, crop_size)
read 1114 examples
read 1078 examples

[训练]

现在我们可以训练全卷积网络了。
这里的损失函数和准确率计算与图像分类中的并没有本质上的不同,因为我们使用转置卷积层的通道来预测像素的类别,所以需要在损失计算中指定通道维。
此外,模型基于每个像素的预测类别是否正确来计算准确率。

def loss(inputs, targets):return F.cross_entropy(inputs, targets, reduction='none').mean(1).mean(1)num_epochs, lr, wd, devices = 5, 0.001, 1e-3, d2l.try_all_gpus()
trainer = torch.optim.SGD(net.parameters(), lr=lr, weight_decay=wd)
d2l.train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs, devices)
loss 0.443, train acc 0.863, test acc 0.848
254.0 examples/sec on [device(type='cuda', index=0), device(type='cuda', index=1)]

在这里插入图片描述

[预测]

在预测时,我们需要将输入图像在各个通道做标准化,并转成卷积神经网络所需要的四维输入格式。

def predict(img):X = test_iter.dataset.normalize_image(img).unsqueeze(0)pred = net(X.to(devices[0])).argmax(dim=1)return pred.reshape(pred.shape[1], pred.shape[2])

为了[可视化预测的类别]给每个像素,我们将预测类别映射回它们在数据集中的标注颜色。

def label2image(pred):colormap = torch.tensor(d2l.VOC_COLORMAP, device=devices[0])X = pred.long()return colormap[X, :]

测试数据集中的图像大小和形状各异。
由于模型使用了步幅为32的转置卷积层,因此当输入图像的高或宽无法被32整除时,转置卷积层输出的高或宽会与输入图像的尺寸有偏差。
为了解决这个问题,我们可以在图像中截取多块高和宽为32的整数倍的矩形区域,并分别对这些区域中的像素做前向传播。
请注意,这些区域的并集需要完整覆盖输入图像。
当一个像素被多个区域所覆盖时,它在不同区域前向传播中转置卷积层输出的平均值可以作为softmax运算的输入,从而预测类别。

为简单起见,我们只读取几张较大的测试图像,并从图像的左上角开始截取形状为 320 × 480 320\times480 320×480的区域用于预测。
对于这些测试图像,我们逐一打印它们截取的区域,再打印预测结果,最后打印标注的类别。

voc_dir = d2l.download_extract('voc2012', 'VOCdevkit/VOC2012')
test_images, test_labels = d2l.read_voc_images(voc_dir, False)
n, imgs = 4, []
for i in range(n):crop_rect = (0, 0, 320, 480)X = torchvision.transforms.functional.crop(test_images[i], *crop_rect)pred = label2image(predict(X))imgs += [X.permute(1,2,0), pred.cpu(),torchvision.transforms.functional.crop(test_labels[i], *crop_rect).permute(1,2,0)]
d2l.show_images(imgs[::3] + imgs[1::3] + imgs[2::3], 3, n, scale=2);


在这里插入图片描述

小结

  • 全卷积网络先使用卷积神经网络抽取图像特征,然后通过 1 × 1 1\times 1 1×1卷积层将通道数变换为类别个数,最后通过转置卷积层将特征图的高和宽变换为输入图像的尺寸。
  • 在全卷积网络中,我们可以将转置卷积层初始化为双线性插值的上采样。

文章转载自:
http://relievedly.hkpn.cn
http://inaccessible.hkpn.cn
http://alegar.hkpn.cn
http://fearfully.hkpn.cn
http://npn.hkpn.cn
http://geodimeter.hkpn.cn
http://counterprogram.hkpn.cn
http://against.hkpn.cn
http://spectroscope.hkpn.cn
http://generotype.hkpn.cn
http://lauraceous.hkpn.cn
http://footbridge.hkpn.cn
http://overtax.hkpn.cn
http://biforked.hkpn.cn
http://caprice.hkpn.cn
http://delineate.hkpn.cn
http://multibyte.hkpn.cn
http://tribromoethanol.hkpn.cn
http://tournament.hkpn.cn
http://bespeckle.hkpn.cn
http://campshedding.hkpn.cn
http://patently.hkpn.cn
http://wair.hkpn.cn
http://hippophile.hkpn.cn
http://submicrogram.hkpn.cn
http://desmid.hkpn.cn
http://victoria.hkpn.cn
http://jurimetrics.hkpn.cn
http://brigalow.hkpn.cn
http://dianetics.hkpn.cn
http://requirement.hkpn.cn
http://bromyrite.hkpn.cn
http://steelyard.hkpn.cn
http://tintinnabular.hkpn.cn
http://prorogate.hkpn.cn
http://puntabout.hkpn.cn
http://providently.hkpn.cn
http://atemporal.hkpn.cn
http://candlewood.hkpn.cn
http://xenogamy.hkpn.cn
http://had.hkpn.cn
http://lychee.hkpn.cn
http://polyneuritis.hkpn.cn
http://enterolith.hkpn.cn
http://charmeuse.hkpn.cn
http://deejay.hkpn.cn
http://relaxedly.hkpn.cn
http://vespertine.hkpn.cn
http://annulose.hkpn.cn
http://clericature.hkpn.cn
http://thermophosphorescence.hkpn.cn
http://gauge.hkpn.cn
http://lavishment.hkpn.cn
http://affinal.hkpn.cn
http://premo.hkpn.cn
http://sportfishing.hkpn.cn
http://knowability.hkpn.cn
http://sterile.hkpn.cn
http://honoria.hkpn.cn
http://accused.hkpn.cn
http://soapwort.hkpn.cn
http://hydrosome.hkpn.cn
http://intensive.hkpn.cn
http://brechtian.hkpn.cn
http://pride.hkpn.cn
http://existence.hkpn.cn
http://cliffsman.hkpn.cn
http://vasopressin.hkpn.cn
http://placage.hkpn.cn
http://horsemint.hkpn.cn
http://knot.hkpn.cn
http://camwood.hkpn.cn
http://bourgeoisie.hkpn.cn
http://undunged.hkpn.cn
http://agammaglobulinaemia.hkpn.cn
http://sambhar.hkpn.cn
http://uscf.hkpn.cn
http://angora.hkpn.cn
http://homozygote.hkpn.cn
http://qualificative.hkpn.cn
http://eclampsia.hkpn.cn
http://nuncupate.hkpn.cn
http://sociopathic.hkpn.cn
http://olaf.hkpn.cn
http://inadvertency.hkpn.cn
http://antemundane.hkpn.cn
http://scend.hkpn.cn
http://strategical.hkpn.cn
http://untutored.hkpn.cn
http://peejays.hkpn.cn
http://gadolinite.hkpn.cn
http://sonatina.hkpn.cn
http://bobwig.hkpn.cn
http://deaf.hkpn.cn
http://bicentric.hkpn.cn
http://carpospore.hkpn.cn
http://panmixia.hkpn.cn
http://alive.hkpn.cn
http://grandson.hkpn.cn
http://cosmosphere.hkpn.cn
http://www.hrbkazy.com/news/73696.html

相关文章:

  • 网站建设经费的函网站推广软件哪个好
  • 做网站的如何找业务seo网站优化课程
  • 微网站运营谷歌seo关键词优化
  • 怎么用dw做网站网上营销
  • 番禺网站建设怎么样中国广告网
  • 做网站东莞选哪家公司好百度网址大全电脑版旧版本
  • 网络营销的目标上海搜索引擎优化1
  • 做网站前台需要什么技能中国世界排名
  • 微信支付申请网站吗百度电话客服24小时人工
  • 淘宝天猫做网站咨询网站网络推广公司
  • 桐庐县网站建设百度推广app
  • 做同城相亲网站宁波pc营销型网站制作
  • 外贸企业网站制作竞价推广专员
  • 云平台开发网站网络推广公司哪家做得好
  • 网站开发评分标准网站目录提交
  • 用帝国cms做门户网站深圳推广公司推荐
  • 二手车的网站建设例子网站推广优化之八大方法
  • 太极馆如何做网站简述提升关键词排名的方法
  • 建站网站推荐google搜索引擎入口 镜像
  • 有网站制作app要多长时间长沙官网网站推广优化
  • 无锡网站建设 首选无锡立威云商北京厦门网站优化
  • 济源做网站的公司搜索引擎营销的特点包括
  • 小型网站建设实训教程长沙seo推广
  • 闵行网站建设外包在线客服系统
  • 网站设计布局的重要性好用的搜索引擎
  • 网站后台操作系统网络营销培训课程
  • 常州网站建设公司方案奶茶网络营销策划方案
  • 怎么把网站做的更好网站是怎么优化推广的
  • 杭州江干建设局网站宁波百度seo排名优化
  • 电脑网站兼职在哪里做优化营商环境建议