22、Pytorch nn.Conv2d

Python,Torch,Daily life,Share,Study 2024-03-24 332 次浏览 次点赞

22、Pytorch nn.Conv2d

CLASS torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', device=None, dtype=None)[
](https://pytorch.org/docs/stable/_modules/torch/nn/modules/conv.html#Conv2d)

Snipaste_2024-03-22_09-36-53.png

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

conv_layer = nn.Conv2d(in_channels=1, out_channels=1, kernel_size=3, stride=1, padding=0, bias=False)
batch_size = 1
# in_channels = 1
input_size = [batch_size, 1, 4, 4]
input_feature_map = torch.randn(input_size)
output_feature_map = conv_layer(input_feature_map)
print(input_feature_map)
print(conv_layer.weight)  # shape:1*1*3*3 out_channels*in_channels*height*width
print(output_feature_map)
'''
tensor([[[[-0.7757, -1.1847, -0.4490,  0.4742],
          [-0.6399,  0.3784, -1.2850, -0.8101],
          [ 0.5036,  1.0672,  0.8179, -0.0068],
          [ 0.3490,  1.0983, -1.2177,  0.3919]]]]) 
Parameter containing:
tensor([[[[-0.3138, -0.0299, -0.2227],
          [ 0.1196,  0.0852,  0.1436],
          [-0.3111, -0.1633,  0.0663]]]], requires_grad=True) 
tensor([[[[-0.1266, -0.3670],
          [ 0.3756,  0.1796]]]], grad_fn=<ConvolutionBackward0>)
'''
output_feature_map1 = F.conv2d(input_feature_map, conv_layer.weight)
print(output_feature_map1)
'''
tensor([[[[-0.0554,  0.1569],
          [ 0.0052,  0.1201]]]], grad_fn=<ConvolutionBackward0>)
tensor([[[[-0.0554,  0.1569],
          [ 0.0052,  0.1201]]]], grad_fn=<ConvolutionBackward0>)
'''

本文由 fmujie 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论

召唤看板娘