文章目录
代码
256×256 -->
224×224
python
import torch
import torch.nn as nn
# 假设 x 是你的特征图,形状为 (4, 32, 256, 256)
x = torch.randn(4, 32, 256, 256)
# 方法一:使用自适应平均池化调整大小
adaptive_avg_pool = nn.AdaptiveAvgPool2d((224, 224))
x_pooled_avg = adaptive_avg_pool(x)
print(x_pooled_avg.shape) # 输出形状应该是 (4, 32, 224, 224)
# 方法二:使用自适应最大池化调整大小
adaptive_max_pool = nn.AdaptiveMaxPool2d((224, 224))
x_pooled_max = adaptive_max_pool(x)
print(x_pooled_max.shape) # 输出形状应该是 (4, 32, 224, 224)
224×224 -->
256×256
python
import torch
import torch.nn as nn
# 创建一个随机的特征图,形状为 (4, 32, 224, 224)
feature_map = torch.randn(4, 32, 224, 224)
# 定义双线性插值的上采样层
upsample = nn.Upsample(size=(256, 256), mode='bilinear', align_corners=False)
# 应用上采样
upsampled_feature_map = upsample(feature_map)
print(upsampled_feature_map.shape) # 输出应为 (4, 32, 256, 256)