比较与torch.nn.Conv2d的功能差异

查看源文件

torch.nn.Conv2d

torch.nn.Conv2d(
    in_channels=120,
    out_channels=240,
    kernel_size=4,
    stride=1,
    padding=0,
    padding_mode='zeros',
    dilation=1,
    groups=1,
    bias=True
)

更多内容详见torch.nn.Conv2d

mindspore.nn.Conv2d

class mindspore.nn.Conv2d(
    in_channels=120,
    out_channels=240,
    kernel_size=4,
    stride=1,
    pad_mode='same',
    padding=0,
    dilation=1,
    group=1,
    has_bias=False,
    weight_init='normal',
    bias_init='zeros',
    data_format='NCHW'
)(input_x)

更多内容详见mindspore.nn.Conv2d

使用方式

PyTorch:默认不对输入进行填充,bias为True。

MindSpore:默认对输入进行填充,使输出与输入维度一致,如果不需要padding,可以将参数设为’valid’。默认has_bias为False。

代码示例

import mindspore as ms
import mindspore.nn as nn
import torch
import numpy as np

# In MindSpore
net = nn.Conv2d(120, 240, 4, stride=2, has_bias=True, weight_init='normal')
x = ms.Tensor(np.ones([1, 120, 1024, 640]), ms.float32)
output = net(x).shape
print(output)
# Out:
# (1, 240, 512, 320)

# In MindSpore
net = nn.Conv2d(120, 240, 4, stride=2, pad_mode='valid', has_bias=True, weight_init='normal')
x = ms.Tensor(np.ones([1, 120, 1024, 640]), ms.float32)
output = net(x).shape
print(output)
# Out:
# (1, 240, 511, 319)

# In PyTorch
m = torch.nn.Conv2d(120, 240, 4, stride=2)
input = torch.rand(1, 120, 1024, 640)
output = m(input)
print(output.shape)
# Out:
# torch.Size([1, 240, 511, 319])