如何使用Keras TensorBoard回调进行网格搜索

问题描述 投票:9回答:2

我正在使用Keras TensorBoard回调。我想运行网格搜索并可视化张量板中每个模型的结果。问题是不同运行的所有结果合并在一起,损失情节是这样的混乱:enter image description here

如何重命名每次运行以获得类似于此的内容:enter image description here

这里是网格搜索的代码:

df = pd.read_csv('data/prepared_example.csv')

df = time_series.create_index(df, datetime_index='DATE', other_index_list=['ITEM', 'AREA'])

target = ['D']
attributes = ['S', 'C', 'D-10','D-9', 'D-8', 'D-7', 'D-6', 'D-5', 'D-4',
       'D-3', 'D-2', 'D-1']

input_dim = len(attributes)
output_dim = len(target)

x = df[attributes]
y = df[target]

param_grid = {'epochs': [10, 20, 50],
              'batch_size': [10],
              'neurons': [[10, 10, 10]],
              'dropout': [[0.0, 0.0], [0.2, 0.2]],
              'lr': [0.1]}

estimator = KerasRegressor(build_fn=create_3_layers_model,
                           input_dim=input_dim, output_dim=output_dim)


tbCallBack = TensorBoard(log_dir='./Graph', histogram_freq=0, write_graph=True, write_images=False)

grid = GridSearchCV(estimator=estimator, param_grid=param_grid, n_jobs=-1, scoring=bug_fix_score,
                            cv=3, verbose=0, fit_params={'callbacks': [tbCallBack]})

grid_result = grid.fit(x.as_matrix(), y.as_matrix())
python tensorflow scikit-learn keras tensorboard
2个回答
4
投票

我认为没有办法将“per-run”参数传递给GridSearchCV。也许最简单的方法是将KerasRegressor子类化为你想要的。

class KerasRegressorTB(KerasRegressor):

    def __init__(self, *args, **kwargs):
        super(KerasRegressorTB, self).__init__(*args, **kwargs)

    def fit(self, x, y, log_dir=None, **kwargs):
        cbs = None
        if log_dir is not None:
            params = self.get_params()
            conf = ",".join("{}={}".format(k, params[k])
                            for k in sorted(params))
            conf_dir = os.path.join(log_dir, conf)
            cbs = [TensorBoard(log_dir=conf_dir, histogram_freq=0,
                               write_graph=True, write_images=False)]
        super(KerasRegressorTB, self).fit(x, y, callbacks=cbs, **kwargs)

您会像以下一样使用它:

# ...

estimator = KerasRegressorTB(build_fn=create_3_layers_model,
                             input_dim=input_dim, output_dim=output_dim)

#...

grid = GridSearchCV(estimator=estimator, param_grid=param_grid,
n_jobs=1, scoring=bug_fix_score,
                  cv=2, verbose=0, fit_params={'log_dir': './Graph'})

grid_result = grid.fit(x.as_matrix(), y.as_matrix())

更新:

由于GridSearchCV由于交叉验证而不止一次地运行相同的模型(即相同的参数配置),因此先前的代码将在每次运行中放置多条迹线。查看源(herehere),似乎没有办法检索“当前拆分ID”。同时,您不应该只检查现有文件夹并根据需要添加子修补程序,因为这些作业并行运行(至少可能,但我不确定Keras / TF是否属于这种情况)。你可以尝试这样的事情:

import itertools
import os

class KerasRegressorTB(KerasRegressor):

    def __init__(self, *args, **kwargs):
        super(KerasRegressorTB, self).__init__(*args, **kwargs)

    def fit(self, x, y, log_dir=None, **kwargs):
        cbs = None
        if log_dir is not None:
            # Make sure the base log directory exists
            try:
                os.makedirs(log_dir)
            except OSError:
                pass
            params = self.get_params()
            conf = ",".join("{}={}".format(k, params[k])
                            for k in sorted(params))
            conf_dir_base = os.path.join(log_dir, conf)
            # Find a new directory to place the logs
            for i in itertools.count():
                try:
                    conf_dir = "{}_split-{}".format(conf_dir_base, i)
                    os.makedirs(conf_dir)
                    break
                except OSError:
                    pass
            cbs = [TensorBoard(log_dir=conf_dir, histogram_freq=0,
                               write_graph=True, write_images=False)]
        super(KerasRegressorTB, self).fit(x, y, callbacks=cbs, **kwargs)

我正在使用os调用兼容Python 2,但如果你使用的是Python 3,你可以考虑使用更好的pathlib module进行路径和目录处理。

注意:我之前忘记提及它,但为了以防万一,请注意,传递write_graph=True将记录每次运行的图形,这取决于您的模型,可能意味着很多(相对而言)这个空间。这同样适用于write_images,虽然我不知道功能需要的空间。


2
投票

这很容易,只需将日志保存到单独的目录中,并使用连接参数字符串作为目录名称:

以下是使用日期作为运行名称的示例:

from datetime import datetime

datetime_str = ('{date:%Y-%m-%d-%H:%M:%S}'.format(date=datetime.now()))
callbacks = [
    ModelCheckpoint(model_filepath, monitor='val_loss', save_best_only=True, verbose=0),
    TensorBoard(log_dir='./logs/'+datetime_str, histogram_freq=0, write_graph=True, write_images=True),
]

history = model.fit_generator(
    generator=generator.batch_generator(is_train=True),
    epochs=config.N_EPOCHS,
    steps_per_epoch=100,
    validation_data=generator.batch_generator(is_train=False),
    validation_steps=10,
    verbose=1,
    shuffle=False,
    callbacks=callbacks)
© www.soinside.com 2019 - 2024. All rights reserved.