【问题标题】:Configure Parameters using gin-config and importlib使用 gin-config 和 importlib 配置参数
【发布时间】:2020-02-20 15:26:24
【问题描述】:

我正在使用 gin-config 来配置不同类的超参数。这对于以经典方式导入的模块非常有效。但是,如何配置一个参数,在使用 importlib 导入的类中使用?

在 main.py 中运行

import gin
import importlib

gin.parse_config_file('config.gin')
module = importlib.import_module('src.external.SomeModule')
_class = getattr(module, 'SomeClass')

This is the externally defined module in src.external.SomeModule
@gin.configurable
SomeClass:
    def __init__(self, variable):
        self.variable = variable

这是“config.gin”文件

SomeClass.variable=0

但是,如果我们这样定义,我们会得到:

Traceback (most recent call last):
  File "main_test.py", line 291, in <module>
    gin.parse_config_file(args.config_path)
  File "/site-packages/gin/config.py", line 1599, in parse_config_file
    parse_config(f, skip_unknown=skip_unknown)
  File "/site-packages/gin/config.py", line 1517, in parse_config
    bind_parameter((scope, selector, arg_name), value)
  File "/contextlib.py", line 130, in __exit__
    self.gen.throw(type, value, traceback)
  File "/site-packages/gin/utils.py", line 68, in try_with_location
    augment_exception_message_and_reraise(exception, _format_location(location))
  File "/site-packages/gin/utils.py", line 49, in augment_exception_message_and_reraise
    six.raise_from(proxy.with_traceback(exception.__traceback__), None)
  File "<string>", line 3, in raise_from
  File "/site-packages/gin/utils.py", line 66, in try_with_location
    yield
  File "/site-packages/gin/config.py", line 1517, in parse_config
    bind_parameter((scope, selector, arg_name), value)
  File "/site-packages/gin/config.py", line 643, in bind_parameter
    pbk = ParsedBindingKey(binding_key)
  File "/site-packages/gin/config.py", line 508, in __new__
    raise ValueError("No configurable matching '{}'.".format(selector))
ValueError: No configurable matching 'src.data.SomeModule.SomeClass'.
  In file "config/cnn_test.gin", line 35
    src.external.SomeModule.SomeClass.variable=0.

【问题讨论】:

    标签: python python-importlib


    【解决方案1】:

    我认为您只需在导入后将gin.parse_config_file('config.gin') 移至。根据杜松子酒README

    最后,在定义或导入所有可配置的类或函数后,解析您的配置文件以绑定您的配置...

    试试这个:

    module = importlib.import_module('src.external.SomeModule')
    _class = getattr(module, 'SomeClass')
    gin.parse_config_file('config.gin')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-26
      • 1970-01-01
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 2018-07-11
      • 1970-01-01
      相关资源
      最近更新 更多