当前位置:首页 » python教程 » 正文

pytorch AvgPool2d函数使用详解

看: 967次  时间:2020-12-17  分类 : python教程

我就废话不多说了,直接上代码吧!

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np



input = Variable(torch.Tensor([[[1, 3, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7]], [[1, 3, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7]]]))
print("input shape",input.shape)
c = F.avg_pool1d(input, kernel_size=3, stride=2)
print(c)
print("c shape:",c.shape)

# m = nn.AvgPool2d(3, stride=2)
m = nn.AvgPool2d((2, 2), stride=(2, 2))
input = Variable(torch.randn(20, 18, 50, 32)) # bach是20,图片size是50*31,chanel是18(通道是18,也就是每张图有18个fature map)
input = np.array([[[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]],
          [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]],
         [[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]],
          [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]]]) #size2*2*4*4
print("input shape:",input.shape)
input = Variable(torch.FloatTensor(input))
output = m(input)
print(output)
print("output shape:",output.shape)#(2,2,2,2)

输出:

input shape torch.Size([2, 2, 7])
tensor([[[ 2.3333, 4.0000, 6.0000],
     [ 2.0000, 4.0000, 6.0000]],

    [[ 2.3333, 4.0000, 6.0000],
     [ 2.0000, 4.0000, 6.0000]]])
c shape: torch.Size([2, 2, 3])
input shape: (2, 2, 4, 4)
tensor([[[[ 1.5000, 3.5000],
     [ 1.5000, 3.5000]],

     [[ 1.5000, 3.5000],
     [ 1.5000, 3.5000]]],


    [[[ 1.5000, 3.5000],
     [ 1.5000, 3.5000]],

     [[ 1.5000, 3.5000],
     [ 1.5000, 3.5000]]]])
output shape: torch.Size([2, 2, 2, 2])

pytorch中的F.avg_pool1d()平均池化操作作用于一维,input的维度是三维比如[2,2,7]。F.avg_pool1d()中核size是3,步长是2表示每三个数取平均,每隔两个数取一次.比如[1,3,3,4,5,6,7]安照3个数取均值,两步取一次,那么结果就是[ 2.3333 ,4 ,6 ],也就是核是一维的,也只作用于一个维度。按照池化操作计算公式input size为[2,2,7],kernel size为3,步长为2,则输出维度计算(7-3)/2+1=3所以输出维度是[2,2,3],这与输出结果是一致的。

pytorch中的F.avg_pool2d(),input是维度是4维如[2,2,4,4],表示这里批量数是2也就是两张图像,这里应该是有通道(feature map)数量是2,图像是size是4*4的.核size是(2,2)步长是(2,2)表示被核覆盖的数取平均,横向纵向的步长都是2.那么核是二维的,所以取均值时也是覆盖二维取的。输出中第一个1.5的计算是:1+2+1+2/4=1.5.表示第一张图像左上角的四个像素点的均值。按照池化操作计算公式input size为[2,2,4,4],kernel size为2*2,步长为2,则输出维度计算(4-2)/2+1=2所以输出维度是[2,2,2,2],这与输出结果是一致的。

以上这篇pytorch AvgPool2d函数使用详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持python博客。

标签:numpy  

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!