卷积操作(pytorch实现):
1、了解一下基础函数
(1)Torch.nn.Conv2d(in_channels,out_channels,kernel_size,stride=1,padding=0,dilation=1,groups=1,bias=True)
in_channels:输入维度 (援引:https://www.cnblogs.com/siyuan1998/p/10809646.html)
out_channels:输出维度
kernel_size:卷积核大小
stride:步长大小
padding:补0
dilation:kernel间距
(2)了解四种分布,生成张量(援引:https://blog.csdn.net/wangwangstone/article/details/89815661)
均匀分布
torch.rand(*sizes, out=None) → Tensor
标准正态分布
torch.randn(*sizes, out=None) → Tensor
离散正态分布
torch.normal(means, std, out=None) → → Tensor
线性间距向量
torch.linspace(start, end, steps=100, out=None) → Tensor
(3)张量的理解(援引:https://blog.csdn.net/qq_25948717/article/details/80310020)
(4)feature map大小计算方法(援引:https://blog.csdn.net/qq_28424679/article/details/78665273)
output :featuremap计算公式是:
output_h =(originalSize_h+padding*2-kernelSize_h)/stride +1
(5)数据类型的查看,以及数据形状查看
数据类型的查看 变量x,x.type()
数据形状查看 张量x,x.shape
2、实操代码:(援引:https://blog.csdn.net/jacke121/article/details/85929638)
import torch
import torch.nn as nn
m = nn.Conv2d(2, 2, 3, stride=2)
''' 定义二维卷积Conv2d,输入通道数in_channels,输出通道数out_channels(间接定义了卷积的个数),卷积的大小kernel_size(3*3),
stride=2 卷积移动的步长。
'''
# Torch.nn.Conv2d(in_channels,out_channels,kernel_size,stride=1,padding=0,dilation=1,groups=1,bias=True)
input = torch.randn(1, 2, 5, 7)# 输入为 大小(宽为5,高为7)5*7,深度为2(也可理解为通道数)
'''
综上可以推算出 输出的featuremap :2*3,深度为2。
'''
output = m(input)
print("输入图片(2张):")
print(input)
print("卷积的权重:")
print(m.weight)
print("卷积的偏重:")
print(m.bias)
print("二维卷积后的输出:")
print(output)
print("输出的尺度:")
print(output.size())
convBlockOne = 0
convBlockTwo = 0
convBlockOne1 = 0
convBlockTwo1 = 0
for i in range(3):
for j in range(3):
# 第一个卷积核与图片对应相乘
convBlockOne += m.weight[0][0][i][j] * input[0][0][i][j] \
+ m.weight[0][1][i][j] * input[0][1][i][j]
# 第二个卷积核与图片对应相乘
convBlockTwo += m.weight[1][0][i][j] * input[0][0][i][j] \
+ m.weight[1][1][i][j] * input[0][1][i][j]
# # 第一个卷积核与图片对应相乘
# convBlockOne1 += m.weight[0][0][i][j] * input[0][0][i][j]+ m.weight[0][1][i][j] * input[0][1][i][j]
# # 第二个卷积核与图片对应相乘
# convBlockTwo1 += m.weight[1][0][i][j] * input[0][0][i][j]+ m.weight[1][1][i][j] * input[0][1][i][j]
convBlockOne += m.bias[0]
convBlockTwo += m.bias[1]
# convBlockOne1 += m.bias[0]
# convBlockTwo1 += m.bias[1]
print("第一个卷积核的输出:")
print(convBlockOne)
print("输出的大小",type(convBlockOne),convBlockOne.shape)
print("第二个卷积核的输出:")
print(convBlockTwo)
# print("去掉斜杠后", convBlockOne1)
# print("去掉斜杠后", convBlockTwo1)
其实实操代码的博主 得到的 convBlockOne 、convBlockTwo都是卷积核在 图片上运算后得到的一个数,
还有,代码中的斜杠(‘\’)是换行的意思,笔者之前接触python太少了,所以现在才懂!这样写就是一行太长写不下,所以采用换行,这样写python代码是个好习惯。如下图:
文章写得有点赘述,希望笔者能帮到大家!