0%

pyYAML Usage

pyYAML Usage

使用 yaml 文件配置模型以及训练参数,方便调参数!😉

借鉴文章:https://zhuanlan.zhihu.com/p/42678768

安装

1
pip install PyYAML

YAML 基本语法

  • 与Python一样采用缩进区分层级,需要同一层级文件缩进相同,但是不能用TAB,只能使用空格;

  • # 表示注释,从它开始到行尾都被忽略;

  • 大小写敏感;

  • - 开头,整个文件会被转换为list,其中 - 后的内容属于一个字典;

  • : 前后的内容转换为 dictionary 的键值对;

  • 单引号内的内容按照字符串输出,不会变成转移字符,双引号内内容存在转义字符会转换

list

parameters.yaml 内容 & .py:

1
2
3
4
# exchange to list
- a
- b
- c
1
2
3
4
5
6
7
import yaml
from yaml import CLoader as Loader

f = open('parameters.yml', encoding='utf-8')
para = yaml.load(f, Loader)
print(type(para))
print(para)

输出:

1
2
<class 'list'>
['a', 'b', 'c']

dictionary

.yml & .py

1
2
3
4
# exchange to dictionary
name: zhangsan
age: 30
nation: China

输出:

1
2
<class 'dict'>
{'name': 'zhangsan', 'age': 30, 'nation': 'China'}

混合转换

1
2
3
4
5
6
7
# exchange to dictionary
- name: zhangsan
age: 30
nation: China
- name: lisi
age: 20
nation: China

输出:

1
2
3
<class 'list'>
[{'name': 'zhangsan', 'age': 30, 'nation': 'China'},
{'name': 'lisi', 'age': 20, 'nation': 'China'}]

pyYAML Usage

import package

1
import yaml  # import this package

load()

加载 yaml 文件,返回一个 pyYAML 对象,这个对象是一个包含了键值对的 listdict

我们一般使用 load() 就够了

1
2
3
4
5
6
7
8
9
10
11
import yaml
from yaml import CLoader as Loader

f = open('parameters.yml', encoding='utf-8')
para = yaml.load(f, Loader)
total_epoch = para['total_epochs']
batch_size = para['batch_size']
learning_rate = float(para['lr'])
target_acc = para['target_acc']
model_name = para['model']
dataset = para['dataset']

dump()

将键值对,转换成 yaml 格式

Donate comment here.