import torch
in_channels,out_channels = 5,10
##输入通道数量 输出通道数量
width,height = 100,100
kernel_size = 3
#也可以用[5,3]这样的元组
#卷积核的大小,也就是filter的大小
batch_size = 1
input = torch.randn(batch_size,
in_channels,
width,
height)
conv_layer = torch.nn.Conv2d(in_channels,
out_channels,
kernel_size = kernel_size)
output = conv_layer(input)
print(input.shape)
#[1, 5, 100, 100] batch,5个通道,100 *100
print(output.shape)
print(conv_layer.weight.shape)
#[10, 5, 3, 3] 输入,输出,卷积核大小
在这里面imput的输入通道(in_channels)和conv_layer的in_channels要相同
1-如果想让input和output维度相同–padding填充
也就是在外面进行填充,将55填成77
代码
import torch
input = [3,4,6,5,7,
2,4,6,8,2,
1,6,7,8,4,
9,7,4,6,2,
3,7,5,4,1]
input = torch.Tensor(input).view(1,1,5,5)
###转换成tensor,维度是 batch,channel,5*5
conv_layer = torch.nn.Conv2d(1,1,kernel_size=3,padding=1,bias = False)
###在这里输入是一个通道,输出也是一个通道,bias = False不加偏置量
kernel = torch.Tensor([1,2,3,4,5,6,7,8,9]).view(1,1,3,3)
#输出通道,输入通道,3*3
conv_layer.weight.data = kernel.data
##卷积层的权重进行初始化
output = conv_layer(input)
print(output)
2-有效降低高度和宽度–stride = 2,可以增加步长
conv_layer = torch.nn.Conv2d(1,1,kernel_size=3,stride=2,bias = False)
最大池化层–默认stride = 2,在每一组中找出最大值
代码
import torch
input = [3,4,6,5,
2,4,6,8,
1,6,7,8,
9,7,4,6]
input = torch.Tensor(input).view(1,1,4,4)
maxpooling_layer = torch.nn.MaxPool2d(kernel_size=2)
##默认stride = 2,卷积核大小也为2
output = maxpooling_layer(input)
print(output)
实现一个简单的神经网络
代码
class Net(torch.nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = torch.nn.Conv2d(1,10,kernel_size=5)
self.conv2 = torch.nn.Conv2d(10,20,kernel_size=5)
self.pooling = torch.nn.MaxPool2d(2)
##卷积核大小为2
self.fc = torch.nn.Linear(320,10)
def forward(self,x):
###将(n,1,28,28)展开为(n,784)
batch_size = x.size(0)
##取出n,batch
x = F.relu(self.pooling(self.conv1(x)))
x = F.relu(self.pooling(self.conv2(x)))
x = x.view(batch_size,-1)
##拉伸成单列
x = self.fc(x)
return x