【问题标题】:Keras + TensorFlow Realtime training chartKeras + TensorFlow 实时训练图
【发布时间】:2017-11-28 12:19:54
【问题描述】:

我在 Jupyter 笔记本中运行了以下代码:

# Visualize training history
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
import numpy
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
# load pima indians dataset
dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:,0:8]
Y = dataset[:,8]
# create model
model = Sequential()
model.add(Dense(12, input_dim=8, kernel_initializer='uniform', activation='relu'))
model.add(Dense(8, kernel_initializer='uniform', activation='relu'))
model.add(Dense(1, kernel_initializer='uniform', activation='sigmoid'))
# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# Fit the model
history = model.fit(X, Y, validation_split=0.33, epochs=150, batch_size=10, verbose=0)
# list all data in history
print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

代码收集 epochs 历史,然后显示进度历史。


问:如何在训练时更改图表,以便实时查看变化?

【问题讨论】:

    标签: python machine-learning tensorflow keras jupyter-notebook


    【解决方案1】:

    在 Jupyter Notebook for Keras 中有livelossplot Python 包用于实时训练损失图(免责声明:我是作者)。

    from livelossplot import PlotLossesKeras
    
    model.fit(X_train, Y_train,
              epochs=10,
              validation_data=(X_test, Y_test),
              callbacks=[PlotLossesKeras()],
              verbose=0)
    

    要了解它是如何工作的,请查看它的源代码,尤其是这个文件:https://github.com/stared/livelossplot/blob/master/livelossplot/outputs/matplotlib_plot.pyfrom IPython.display import clear_outputclear_output(wait=True))。

    公平的免责声明:it does interfere with Keras output

    【讨论】:

    • 这仅适用于Jupyter 笔记本吗?
    • 我在使用库后有一个问题,livelossplot。我观察到以下指标:验证(最小值:113.068,最大值:1852.994,当前:117.239)。我清楚地理解了“min”和“max”的含义,但“cur”实际上是什么意思?
    • 现在它不仅适用于 Jupyter。
    • @Dinesh "Current",确定吗?
    【解决方案2】:

    Keras 附带一个callback for TensorBoard

    您可以轻松地将此行为添加到您的模型中,然后只需在日志数据之上运行 tensorboard。

    callbacks = [TensorBoard(log_dir='./logs')]
    result = model.fit(X, Y, ..., callbacks=callbacks)
    

    然后在你的外壳上:

    tensorboard --logdir=/logs
    

    如果您需要在笔记本中使用,您也可以编写自己的回调以在训练时获取指标:

     class LogCallback(Callback):
    
        def on_epoch_end(self, epoch, logs=None):
            print(logs["train_accuracy"])
    

    这将在当前 epoch 结束时获得训练准确度并打印出来。 There's some good documentation around it on the official keras site.

    【讨论】:

    • 但是 TensorBoard 是向您显示实时训练数据还是只能在训练模型后才能看到?
    • @LucasFarias 你可以使用 Tensorboard 实时查看