【问题标题】:Keras keyboard interrupt to stop training?Keras键盘中断停止训练?
【发布时间】:2018-10-31 15:47:40
【问题描述】:

在tensorflow中似乎有办法做到这一点:Keyboard interrupt tensorflow run and save at that point

Keras 有这样的东西吗?

【问题讨论】:

    标签: keras deep-learning


    【解决方案1】:

    您可以捕获KeyboardInterrupt 异常并将模型保存在except 块中:

    save_path = './keras-saves/_latest.ckpt'
    try:
        model.fit(x_train, y_train,
                  batch_size=batch_size,
                  epochs=epochs)
    except KeyboardInterrupt:
        model.save(save_path)
        print('Output saved to: "{}./*"'.format(save_path))
    

    【讨论】:

    • 顺便说一句,这在 linux 上运行良好,但在 windows 上似乎有问题。我尝试在 Windows 10 上的 keras 脚本中使用它,该脚本也导入 sklearn,然后 KeyboardInterrupt 不再起作用。
    【解决方案2】:

    我发现最好的方法是使用屏幕上的鼠标位置作为输入。

    在以下示例中,如果您将鼠标移到左边缘 (x

    def queryMousePosition():
        from ctypes import windll, Structure, c_long, byref
        class POINT(Structure): _fields_ = [("x", c_long), ("y", c_long)]
        pt = POINT()
        windll.user32.GetCursorPos(byref(pt))
        return pt.x, pt.y  # %timeit queryMousePosition()
    
    
    class TerminateOnFlag(keras.callbacks.Callback):
        def on_batch_end(self, batch, logs=None):
            mouse_x, mouse_y = queryMousePosition()
            if mouse_x < 10:
                self.model.stop_training = True
    
    callbacks=[keras.callbacks.ReduceLROnPlateau(), TerminateOnFlag()]
    
    model.fit_generator(..., callbacks=callbacks, ...)
    

    (您可以通过鼠标位置轻松添加不同类型的在线交互作为输入...)

    【讨论】:

    • 我喜欢这种方法,因为您可以在退出火车循环后继续进行绘图和预测
    猜你喜欢
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 2020-12-25
    • 2016-09-14
    • 1970-01-01
    相关资源
    最近更新 更多