ML Collections的介绍(一)
在看一篇论文的源码时,看到import ml_collections这行代码,系统报错,经过寻找之后发现并不是源码中的一个文件,之后感觉应该是一个深度学习的安装包,然后就在网上搜索这个包的安装过程,却没有任何信息,于是自己直接尝试了pip install ml-collections,于是就安装成功了。今天在github上搜索了这个安装包,潜心学习了一下。
ML Collections
ML Collections是为ML use cases而设计的一个Python Collections的一个库。它的两个类是ConfigDict
和FrozenConfigDict
,是"dict-like" 的数据结构,以下是ConfigDict
、FrozenConfigDict
和FieldReference
的示例用法,直接上代码吧。
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':