AdaptiveAvgPool1D内部实现

公式:

# average adaptive pool1d
# suppose input data in shape of [N, C, L], `output_size` is m or [m],
# output shape is [N, C, m], adaptive pool divide L dimension
# of input data into m grids averagely and performs poolings in each
# grid to get output.
# adaptive avg pool performs calculations as follow:
#
#     for i in range(m):
#         lstart = floor(i * L / m)
#         lend = ceil((i + 1) * L / m)
#         output[:, :, i] = sum(input[:, :, lstart: lend])/(lstart - lend)
#

import torch
import numpy as np
L = 4
M = 5

input = torch.ones(1, 1, L)
input[0, 0 , 2] = 0
print(input)

AdaptiveAvgPool1D = torch.nn.AdaptiveAvgPool1d(M)
output1 = AdaptiveAvgPool1D(input)
print(output1)

input = np.array(input)
for i in range(M):
    lstart = math.floor(i * L / M)
    lend = math.ceil((i + 1) * L / M)
    print(np.sum(input[:, :, lstart: lend], axis=2) / (lend - lstart))

输出:

tensor([[[1., 1., 0., 1.]]])
tensor([[[1.0000, 1.0000, 0.5000, 0.5000, 1.0000]]])
[[1.]]
[[1.]]
[[0.5]]
[[0.5]]
[[1.]]

参考:

paddle.nn - AdaptiveAvgPool1D - 《百度飞桨 PaddlePaddle v2.0 深度学习教程》 - 书栈网 · BookStack

你可能感兴趣的:(深度学习框架,pytorch,深度学习)