python 读取 yaml 配置文件参数的方法

test_20220105.yaml 内容如下:
decoder: transformer
grad_clip: 5    # 梯度裁剪
accum_grad: 4
max_epoch: 240
log_interval: 100     # 打印日志的步数
optim: adam
shuffle: true
optim_conf:
    lr: 0.002
dataset_conf:
    filter_conf:
        max_length: 40960
        min_length: 0
        token_max_length: 200
        token_min_length: 1
代码示例:
import yaml
config = "test_20220105.yaml"
with open(config, 'r', encoding='utf-8') as fin:
    configs = yaml.load(fin, Loader=yaml.FullLoader)

"""
取key对应的value值的两种方式:
1、configs['key']
2、configs.get('key')
根据下面的例子,显然第一种方式更简单。
"""

# 第一级目录
max_epoch = configs['max_epoch']    # 240
max_epoch = configs.get('max_epoch')    # 240

# 多级目录
max_length = configs['dataset_conf']['filter_conf']['max_length']    # 40960
max_length = configs.get('dataset_conf').get('filter_conf').get('max_length')    # 40960


"""
设置默认值的方法:
configs.get('key', value)    value为默认值
"""

# default=100表示如果configs里面没有 max_epoch 参数,则设置 num_epochs=100;否则,取原来的值。
num_epochs = configs.get('max_epoch', 100)    # 240
type = configs.get('dynamic', 'static')    # static,因为 configs 中没有参数'dynamic'
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ctrl A_ctrl C_ctrl V

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值