NiN网络——pytorch版
import torch
from torch import nn
from d2l import torch as d2l
def nin_block(in_channels,out_channels,kernel_size,strides,padding):
return nn.Sequential(
nn.Conv2d(in_channels,out_channels,kernel_size,strides,padding),
nn.ReLU(),nn.Conv2d(out_channels,out_channels,kernel_size=1),
nn.ReLU(),nn.Conv2d(out_channels,out_channels,kernel_size=1),
nn.ReLU()
)
net = nn.Sequential(
nin_block(1,96,kernel_size=11,strides=4,padding=0),
nn.MaxPool2d(3,stride=2),
nin_block(96,256,kernel_size=5,strides=1,padding=2),
nn.MaxPool2d(2,stride=2),
nin_block(256,384,kernel_size=3,strides=1,padding=1),
nn.MaxPool2d(3,stride=2),
# 以一定的概率将卷积层的某些通道输出变为零,这样可以让模型在训练过程中不过度依赖特定的特征
nn.Dropout(0.5),
# 标签数为10
nin_block(384,10,kernel_size=3,strides=1,padding=1),
# 高宽都变成1,从5x5,变成了1x1
nn.AdaptiveAvgPool2d((1,1)),
# 消掉最后两个维度
nn.Flatten()
)
lr,num_epochs,batch_size=0.1,10,128
train_iter,test_iter=d2l.load_data_fashion_mnist(batch_size=batch_size)
d2l.train_ch6(net,train_iter,test_iter,num_epochs,lr,d2l.try_gpu())
x=torch.rand(size=(1,1,224,224))
for layer in net:
x=layer(x)
print(layer.__class__.__name__,'output shape:\t',x.shape)
作者:Jace Jin
github地址:https://github.com/buxianghua
原创文章版权归作者所有.
欢迎转载,转载时请在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
欢迎转载,转载时请在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.