collections.OrderedDict() 函数使用技巧


Author :Horizon Max

编程技巧篇:各种操作小结

机器视觉篇:会变魔术 OpenCV

深度学习篇:简单入门 PyTorch

神经网络篇:经典网络模型

算法篇:再忙也别忘了 LeetCode


文章目录

  • collections.OrderedDict()
    • 创建 OrderedDict
    • 使用 .items() 读取
    • 修改 OrderedDict
    • 构建神经网络模型

collections.OrderedDict()

python中字典 Dict 是利用hash存储,各元素之间没有顺序 ;
而在 OrderedDict 中是按照 添加顺序存储 的 有序 字典 ;


创建 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()')])

使用 .items() 读取

for key, value in dic.items():
    print(key, value)

输出结果:

conv nn.Conv2d()
norm BatchNorm2d()
relu ReLU()
pool MaxPool2d()

修改 OrderedDict

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)
)


你可能感兴趣的:(各种操作小结,python,OrderedDict,collections,nn)