Author :Horizon Max
✨ 编程技巧篇:各种操作小结
机器视觉篇:会变魔术 OpenCV
深度学习篇:简单入门 PyTorch
神经网络篇:经典网络模型
算法篇:再忙也别忘了 LeetCode
python中字典 Dict
是利用hash存储,各元素之间没有顺序 ;
而在 OrderedDict
中是按照 添加顺序存储 的 有序 字典 ;
import collections
dic = collections.OrderedDict()
dic['conv'] = 'nn.Conv2d()'
dic['norm'] = 'BatchNorm2d()'
dic['relu'] = 'ReLU()'
dic['pool'] = 'MaxPool2d()'
print(dic)
输出结果:
OrderedDict([('conv', 'nn.Conv2d()'), ('norm', 'BatchNorm2d()'), ('relu', 'ReLU()'), ('pool', 'MaxPool2d()')])
for key, value in dic.items():
print(key, value)
输出结果:
conv nn.Conv2d()
norm BatchNorm2d()
relu ReLU()
pool MaxPool2d()
import collections
dic = collections.OrderedDict(conv='nn.Conv1d()', norm='Norm()')
print(dic)
dic['conv'] = 'nn.Conv2d()'
dic['norm'] = 'BatchNorm2d()'
dic['relu'] = 'ReLU()'
dic['pool'] = 'MaxPool2d()'
print(dic)
输出结果:
OrderedDict([('conv', 'nn.Conv1d()'), ('norm', 'Norm()')])
OrderedDict([('conv', 'nn.Conv2d()'), ('norm', 'BatchNorm2d()'), ('relu', 'ReLU()'), ('pool', 'MaxPool2d()')])
同理,也可以用于构建神经网络模型:
import torch.nn as nn
from collections import OrderedDict
features = nn.Sequential(OrderedDict([
('conv', nn.Conv2d(3, 32, kernel_size=7, stride=2, padding=3, bias=False)),
('norm', nn.BatchNorm2d(32)),
('relu', nn.ReLU(inplace=True)),
('pool', nn.MaxPool2d(kernel_size=3, stride=2, padding=1)),
]))
print(features)
输出结果:
Sequential(
(conv): Conv2d(3, 32, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
(norm): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
(pool): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False)
)