学习torch框架中的卷积神经网络,对此进行记录
一维的卷积能处理多维数据
import torch
import torch.nn as nn
import torch.nn.functional as F
x = torch.randn(10, 16, 30, 32, 34)
# batch, channel , height , width
print(x.shape)
class Net_1D(nn.Module):
def __init__(self):
super(Net_1D, self).__init__()
self.layers = nn.Sequential(
nn.Conv1d(in_channels=16, out_channels=16, kernel_size=(3, 2, 2), stride=(2, 2, 1), padding=[2,2,2]),
nn.ReLU()
)
def forward(self, x):
output = self.layers(x)
log_probs = F.log_softmax(output, dim=1)
return log_probs
n = Net_1D() # in_channel,out_channel,kennel,
print(n)
y = n(x)
print(y.shape)
结果:
torch.Size([10, 16, 30, 32, 34])
Net_1D(
(layers): Sequential(
(0): Conv1d(16, 16, kernel_size=(3, 2, 2), stride=(2, 2, 1), padding=[2, 2, 2])
(1): ReLU()
)
)
torch.Size([10, 16, 16, 18, 37])
故:y = [10, 16, 16, 18, 37]
二维卷积可以处理二维数据
import torch
import torch.nn as nn
x = torch.randn(10, 16, 30, 32) # batch, channel , height , width
print(x.shape)
m = nn.Conv2d(16, 33, (3, 2), (2,1)) # in_channel, out_channel ,kennel_size,stride
print(m)
y = m(x)
print(y.shape)
结果:
torch.Size([10, 16, 30, 32])
Conv2d(16, 33, kernel_size=(3, 2), stride=(2, 1))
torch.Size([10, 33, 14, 31])
3.卷积计算过程:
h/w = (h/w - kennel_size + 2padding) / stride + 1
x = ([10,16,30,32]),其中h=30,w=32,对于卷积核长分别是 h:3,w:2 ;对于步长分别是h:2,w:1;padding默认0;
h = (30 - 3 + 20)/ 2 +1 = 27/2 +1 = 13+1 =14
w =(32 - 2 + 2*0)/ 1 +1 = 30/1 +1 = 30+1 =31
batch = 10, out_channel = 33
故: y= ([10, 33, 14, 31])