【问题标题】:Tensorflow: How to train for a length of time instead of epochs?Tensorflow:如何训练一段时间而不是纪元?
【发布时间】:2023-02-25 13:15:04
【问题描述】:

前期研究:
Most relevant tensorflow article
How can I calculate the time spent for overall training a model in Tensorflow (for all epochs)?
Show Estimated remaining time to train a model Tensorflow with large epochs

代码:

y = to_categorical(self.ydata, num_classes=self.vocab_size)
model = Sequential()
model.add(Embedding(self.vocab_size, 10, input_length=1))
model.add(LSTM(1000, return_sequences=True))
model.add(LSTM(1000))
model.add(Dense(1000, activation="relu"))
model.add(Dense(self.vocab_size, activation="softmax"))
keras.utils.plot_model(model, show_layer_names=True)
checkpoint = ModelCheckpoint(modelFilePath, monitor='loss', verbose=1,save_best_only=True, mode='auto')
reduce = ReduceLROnPlateau(monitor='loss', factor=0.2,patience=3, min_lr=0.0001, verbose=1)
tensorboard_Visualization = TensorBoard(log_dir=logdirPath)
model.compile(loss="categorical_crossentropy", optimizer=Adam(lr=0.001))
history = model.fit(self.Xdata, y, epochs=epochs, batch_size=64, callbacks=[checkpoint, reduce, tensorboard_Visualization]).history

灵感来自:

  1. https://www.analyticsvidhya.com/blog/2021/08/predict-the-next-word-of-your-text-using-long-short-term-memory-lstm/
  2. https://towardsdatascience.com/building-a-next-word-predictor-in-tensorflow-e7e681d4f03f

    此代码采用单词“问题”和“答案”列表进行训练。如果您在阅读本文之前猜到了模型的目标,那么您将获得令人印象深刻的背景知识。无论如何,这段代码有效。我现在只想增强它。

    如何在一定时间内训练模型?一个纪元所花费的时间因我为该 AI 提供的文本而异。变化很大,一般在10秒到4分钟左右。我可以用它来近似时间的纪元,但如果存在另一种方法,我会很感激 TensorFlow 资源中的更具体的想法。

    我真的想要一个可用的答案。请在您的解释中添加一些代码,尤其是一些有用的文档将是一个加号。我希望你喜欢这个问题并投赞成票!

    :)

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    如果必须按照您提出问题的方式定义超时,请查看this answer

    但是,准确性会根据您输入的文本而发生很大变化。从极差到过度拟合。所以你最终会花更多的时间来验证。更适合您的问题的是自定义 EarlyStopping

    from tensorflow.keras.callbacks import EarlyStopping
    
    custom_early_stopping = EarlyStopping(
        monitor='val_accuracy', 
        patience=8, 
        min_delta=0.001, 
        mode='max'
    )
    
    history = model.fit(
        # rest of parameters
        callbacks=[custom_early_stopping ] # and rest of callbacks
    )
    

    在此示例中,您将验证准确性设置为性能监视器以确定何时停止训练。我不认为你对低精度训练模型有任何用处,或者仅仅因为你设定了时间就在你击中它之后继续。

    patience=8 表示训练在 8 个 epoch 没有改善的情况下立即终止。 min_delta=0.001 表示验证准确性必须至少提高 0.001 才能算作改进。 mode='max'表示监控数量停止增加时停止。

    【讨论】:

    • 经过测试。太好了,感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2022-07-09
    • 2018-07-06
    • 2019-04-12
    • 2023-03-23
    • 2020-07-08
    • 2021-03-11
    • 1970-01-01
    • 2016-03-09
    相关资源
    最近更新 更多