You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyTorch中nn.ConvTranspose2d如何使用circular填充模式?

解决PyTorch中nn.ConvTranspose2d使用circular填充的方法

截至2024年,PyTorch官方确实未为nn.ConvTranspose2d实现padding_mode='circular',但可以通过两种手动方式模拟该效果:

方法一:手动预填充输入再调用普通ConvTranspose2d

转置卷积的padding逻辑与普通卷积相反,要实现circular填充,可先对输入做循环填充,再使用padding_mode='zeros'的转置卷积(无需额外设置padding参数,避免重复填充)。

示例代码:

import torch
import torch.nn.functional as F
import torch.nn as nn

nz = 100
ngf = 64

# 示例输入:latent vector转换后的4D张量 (batch_size, nz, 1, 1)
input = torch.randn(2, nz, 1, 1)

# 根据转置卷积参数计算填充尺寸:kernel_size=4、stride=1,需在H/W两侧各填充3(4-1=3)
padded_input = F.pad(input, (3, 3, 3, 3), mode='circular')

# 调用无padding的转置卷积
conv_trans = nn.ConvTranspose2d(nz, ngf * 16, 4, 1, 0, bias=False)
output = conv_trans(padded_input)

注意:填充尺寸需根据你的转置卷积参数(kernel_size、stride、output_padding等)调整,核心是让预填充后的输入经过转置卷积后,输出尺寸符合预期,同时模拟circular边界处理。

方法二:用普通Conv2d模拟转置卷积的circular填充效果

转置卷积可看作普通卷积的转置操作,你可以将转置卷积的权重转置后,对输入做circular填充的普通卷积,等价实现circular填充的转置卷积效果。

示例代码:

import torch
import torch.nn as nn
import torch.nn.functional as F

nz = 100
ngf = 64

# 定义原转置卷积层用于获取权重
conv_trans = nn.ConvTranspose2d(nz, ngf * 16, 4, 1, 0, bias=False)
# 转置权重:转置卷积权重格式为[out_channels, in_channels, kH, kW],转置后变为[in_channels, out_channels, kH, kW]
weight = conv_trans.weight.transpose(0, 1)

input = torch.randn(2, nz, 1, 1)
# 调用带circular填充的普通卷积,padding=3匹配kernel_size=4的循环填充需求
output = F.conv2d(input, weight, bias=None, stride=1, padding=3, padding_mode='circular')

该方法需手动处理权重转置和尺寸计算,适合对转置卷积底层逻辑熟悉的场景。


内容的提问来源于stack exchange,提问作者yx feng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 12:07:09