[64, 512, 96, 32] 池化为 [64, 1024, 12, 8] 的 Python 代码实现
[64, 512, 96, 32] 池化为 [64, 1024, 12, 8] 的 Python 代码实现
本示例展示如何使用 Python 代码实现将一个形状为 [64, 512, 96, 32] 的多维数组通过池化操作变为 [64, 1024, 12, 8] 的形状。
import numpy as np
x = np.random.randn(64, 512, 96, 32)
pool_shape = (2, 4, 8, 4)
stride = (2, 4, 8, 4)
N, C, H, W = x.shape
pool_H, pool_W, pool_D, pool_M = pool_shape
stride_H, stride_W, stride_D, stride_M = stride
out_H = (H - pool_H) // stride_H + 1
out_W = (W - pool_W) // stride_W + 1
out_D = (D - pool_D) // stride_D + 1
out_M = (M - pool_M) // stride_M + 1
out = np.zeros((N, C, out_H, out_W, out_D, out_M))
for h in range(out_H):
for w in range(out_W):
for d in range(out_D):
for m in range(out_M):
vert_start = h * stride_H
vert_end = vert_start + pool_H
horiz_start = w * stride_W
horiz_end = horiz_start + pool_W
depth_start = d * stride_D
depth_end = depth_start + pool_D
channel_start = m * stride_M
channel_end = channel_start + pool_M
x_slice = x[:, :, vert_start:vert_end, horiz_start:horiz_end, depth_start:depth_end, channel_start:channel_end]
out[:, :, h, w, d, m] = np.max(x_slice, axis=(2, 3, 4, 5))
print(out.shape) # (64, 512, 12, 8)
代码解释:
- 定义输入数组:
x = np.random.randn(64, 512, 96, 32)定义了一个形状为 [64, 512, 96, 32] 的随机数组作为输入。 - 定义池化参数:
pool_shape = (2, 4, 8, 4)和stride = (2, 4, 8, 4)分别定义了池化窗口大小和步长。 - 计算输出形状: 通过公式
(H - pool_H) // stride_H + 1计算输出数组的每个维度的大小。 - 创建输出数组:
out = np.zeros((N, C, out_H, out_W, out_D, out_M))创建一个形状为 [64, 512, 12, 8] 的全零数组作为输出。 - 遍历输出数组: 使用四个嵌套循环遍历输出数组的每个元素。
- 计算池化区域: 对于每个输出元素,根据步长和池化窗口大小计算对应输入数组的池化区域。
- 执行最大池化:
np.max(x_slice, axis=(2, 3, 4, 5))在池化区域内计算最大值,并将结果赋值给对应的输出元素。 - 输出结果:
print(out.shape)输出最终池化后的数组形状为 (64, 512, 12, 8)。
注意: 本示例使用的是最大池化操作。你可以根据需求修改代码实现其他池化操作,例如平均池化等。
原文地址: https://www.cveoy.top/t/topic/mZA8 著作权归作者所有。请勿转载和采集!