文章目录
1.nn.ReflectionPad2d()
torch.nn.ReflectionPad2d() 是 PyTorch 中的一个模块,用于执行二维反射填充操作。反射填充是一种常用的填充方法,它在输入张量的边界周围以对称方式复制边缘值来扩展输入的尺寸。
torch.nn.ReflectionPad2d(padding)
"""
参数:padding:指定填充的大小。可以是一个整数,表示在每个边界上应用相同的填充大小。也可以是一个长度为 4 的元组 (pad_left, pad_right, pad_top, pad_bottom),分别表示左、右、上、下四个方向的填充大小。
返回值:返回一个执行反射填充操作的模块。
"""
import torch
import torch.nn as nn
# 创建一个输入大小为 (batch_size=1, channels=3, height=4, width=4) 的张量
input_tensor = torch.randn(1, 3, 4, 4)
# 创建一个反射填充层,指定填充大小为 1
reflection_pad = nn.ReflectionPad2d(1)
# 应用反射填充操作
output = reflection_pad(input_tensor)
print("Input shape:", input_tensor.shape)
print("Output shape:", output.shape)
print("Output tensor:")
print(output)
Input shape: torch.Size([1, 3, 4, 4])
Output shape: torch.Size([1, 3, 6, 6])
Output tensor:
tensor([[[[-0.4726, -0.9318, -0.4726, 0.0358, -1.3965, 0.0358],
[ 0.6456, -0.0962, 0.6456, 0.1090, 1.0219, 0.1090],
[-0.4726, -0.9318, -0.4726, 0.0358, -1.3965, 0.0358],
[ 2.1055, 0.1147, 2.1055, -2.0517, 1.6568, -2.0517],
[ 0.2304, 0.2164, 0.2304, -0.8812, -0.2803, -0.8812],
[ 2.1055, 0.1147, 2.1055, -2.0517, 1.6568, -2.0517]],
[[ 0.3650, 0.5981, 0.3650, 0.2102, 1.7905, 0.2102],
[-0.0200, -0.0328, -0.0200, 0.2043, -0.0937, 0.2043],
[ 0.3650, 0.5981, 0.3650, 0.2102, 1.7905, 0.2102],
[ 0.5632, 1.2948, 0.5632, -0.0395, 0.5825, -0.0395],
[ 0.7248, -0.5541, 0.7248, -0.2897, 0.5524, -0.2897],
[ 0.5632, 1.2948, 0.5632, -0.0395, 0.5825, -0.0395]],
[[ 1.3675, -1.0789, 1.3675, 0.1664, 0.4726, 0.1664],
[ 0.5879, -1.2825, 0.5879, -0.0681, -1.1589, -0.0681],
[ 1.3675, -1.0789, 1.3675, 0.1664, 0.4726, 0.1664],
[-0.2540, -0.5877, -0.2540,