3

使用Sacred时,必须将实验配置中的所有变量传递到主函数中,例如

ex = Experiment('iris_rbf_svm')

@ex.config
def cfg():
  C = 1.0
  gamma = 0.7

@ex.automain
def run(C, gamma):
  iris = datasets.load_iris()
  per = permutation(iris.target.size)
  iris.data = iris.data[per]
  iris.target = iris.target[per]
  clf = svm.SVC(C, 'rbf', gamma=gamma)
  clf.fit(iris.data[:90],
          iris.target[:90])
  return clf.score(iris.data[90:],
                   iris.target[90:])

如您所见,在这个实验中,有 2 个变量,Cgamma,它们被传递到主函数中。

在实际场景中,有几十个实验变量,将它们全部传递到主函数中会变得非常混乱。有没有办法将它们全部作为字典传递?或者也许作为具有属性的对象?

一个好的解决方案将导致如下所示:

@ex.automain
def run(config):
    config.C      # Option 1
    config['C']   # Option 2 
4

3 回答 3

4

是的,您可以为此使用特殊值 _config

ex = Experiment('iris_rbf_svm')

@ex.config
def cfg():
  C = 1.0
  gamma = 0.7

@ex.automain
def run(_config):
  C = _config['C']
  gamma = _config['gamma']
于 2019-03-04T11:44:14.477 回答
1

我能找到的最优雅的解决方案

ex = Experiment('iris_rbf_svm')

@ex.config
def cfg():
    C = 1.0
    gamma = 0.7

    params = {'C': C, 'gamma': gamma}

@ex.automain
def run(params):
    iris = datasets.load_iris()
    per = permutation(iris.target.size)
    iris.data = iris.data[per]
    iris.target = iris.target[per]
    clf = svm.SVC(params['C'], 'rbf', gamma=params['gamma'])
    clf.fit(iris.data[:90],
            iris.target[:90])
    return clf.score(iris.data[90:],
                     iris.target[90:])
于 2018-12-04T17:17:14.907 回答
0

git仓库中有一个相关的例子: https ://github.com/IDSIA/sacred/blob/master/examples/08_less_magic.py

您可以直接指定字典(无需创建装饰函数)

from sacred import Experiment
from sacred.observers import FileStorageObserver
from sklearn import svm, datasets, model_selection

ex = Experiment("svm")

ex.add_config(
    {  # Configuration is explicitly defined as dictionary.
        "C": 1.0,
        "gamma": 0.7,
        "kernel": "rbf",
        "seed": 42,
    }
)

并按如下方式使用它:

def get_model(C, gamma, kernel):
    return svm.SVC(C=C, kernel=kernel, gamma=gamma)


@ex.main  # Using main, command-line arguments will not be interpreted in any special way.
def run(_config):
    X, y = datasets.load_breast_cancer(return_X_y=True)
    X_train, X_test, y_train, y_test = model_selection.train_test_split(
        X, y, test_size=0.2
    )
    clf = get_model(
        _config["C"], _config["gamma"], _config["kernel"]
    )  # Parameters are passed explicitly.
    clf.fit(X_train, y_train)
    return clf.score(X_test, y_test)


if __name__ == "__main__":
    ex.run()
于 2019-12-23T19:26:39.077 回答