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

How to use Keras TensorBoard callback for grid search

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

如何重命名每个 运行 有类似的东西:

这里是网格搜索的代码:

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())

我认为没有任何方法可以将 "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 运行由于交叉验证,同一模型(即相同的参数配置)不止一次,前面的代码最终会在每个 运行。查看源代码 (here and here),似乎没有办法检索 "current split 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 将记录一个图表 per 运行,其中,根据您的模型,这可能意味着很多(相对而言)space。这同样适用于 write_images,尽管我不知道该功能需要 space。

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

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

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)