1、采用的自定义卷积神经网络
设计参考了
1.1神经网络结构
输入尺寸为112*112,用了4层卷积网络和2层输出,每层卷积陈的结构如下
1.2代码实现
(1)注意输出层用损失函数CrossEntropyLoss()时不需要
criteon = nn.CrossEntropyLoss()
......................
.....................
loss = criteon(logits, y)
(2)完整代码
# import torch.nn.functional as F
import torch
from torch import optim, nn
class OurConv(nn.Module):
def __init__(self):
super(OurConv,self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(3,32,kernel_size=3,padding=1),
nn.ReLU(),
nn.BatchNorm2d(32),
nn.MaxPool2d(2,2),
nn.Dropout(0.25)
)
self.conv2 = nn.Sequential(
nn.Conv2d(32,64,kernel_size=3,padding=1),
nn.ReLU(),
nn.BatchNorm2d(64),
nn.MaxPool2d(2,2),
nn.Dropout(0.25)
)
self.conv3 = nn.Sequential(
nn.Conv2d(64,128,kernel_size=3,padding=1),
nn.ReLU(),
nn.BatchNorm2d(128),
nn.MaxPool2d(2,2),
nn.Dropout(0.25)
)
self.conv4 = nn.Sequential(
nn.Conv2d(128,256,kernel_size=3,padding=1),
nn.ReLU(),
nn.BatchNorm2d(256),
nn.MaxPool2d(2,2),
nn.Dropout(0.25)
)
self.fc = nn.Sequential(
nn.Linear(256*7*7,256),
nn.Dropout(0.2),
nn.Linear(256,2),
)
def forward(self,x):
x = self.conv1(x)
print("shape1",x.shape)
x = self.conv2(x)
print("shape2",x.shape)
x = self.conv3(x)
print("shape3",x.shape)
x = self.conv4(x)
print("shape4",x.shape)
x = x.view(x.size(0),-1)
x = self.fc(x)
# return F.log_softmax(x,dim=1)
return x
def main():
tmp = torch.randn(64, 3, 112, 112)
out_mode = OurConv()
out = out_mode(tmp)
print('block:', out.shape)
if __name__ == '__main__':
main()
2训练
import torch
from torch import optim, nn
# import visdom
# fr