ML Collections的介绍(一)

ML Collections的介绍(一)

在看一篇论文的源码时,看到import ml_collections这行代码,系统报错,经过寻找之后发现并不是源码中的一个文件,之后感觉应该是一个深度学习的安装包,然后就在网上搜索这个包的安装过程,却没有任何信息,于是自己直接尝试了pip install ml-collections,于是就安装成功了。今天在github上搜索了这个安装包,潜心学习了一下。

ML Collections

ML Collections是为ML use cases而设计的一个Python Collections的一个库。它的两个类是ConfigDictFrozenConfigDict,是"dict-like" 的数据结构,以下是ConfigDictFrozenConfigDictFieldReference的示例用法,直接上代码吧。

Basic Usage

import ml_collections

cfg = ml_collections.ConfigDict()
cfg.float_field = 12.6 #float类型
cfg.integer_field = 123 #int类型
cfg.another_integer_field = 234 #int类型
cfg.nested = ml_collections.ConfigDict() #嵌套了ml_collections.ConfigDict()
cfg.nested.string_field = 'tom' #str类型

print(cfg.integer_field)  # 输出结果 123.
print(cfg['integer_field'])  # 也输出123.

try:
  cfg.integer_field = 'tom'  # 输出会报错错误类型是TypeError,因为这你field是整数类型
except TypeError as e:
  print(e)

cfg.float_field = 12  # int类型也可以指定给float类型.
cfg.nested.string_field = u'bob'  # string可以储存Unicode字符串
print(cfg)

下面是这段代码的输出结果

123
123
Could not override field 'integer_field' (reference). tom is of type <class 'str'> but should be of type <class 'int'> #报错的地方
#以下输出是所有的cfg的结果,以及嵌套的nested
another_integer_field: 234
float_field: 12.0
integer_field: 123
nested:
  string_field: bob

FrozenConfigDict

不可以改变的ConfigDict

import ml_collections
#初始化一个字典
initial_dictionary = {
   
    'int': 1,
    'list': [1, 2],
    'tuple': (1, 2, 3),
    'set': {
   1, 2, 3, 4},
    'dict_tuple_list': 
  • 27
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值