[英]How to save the best model of each epoch with transformers bert in tensorflow
我使用 TFBertModel 和 Tensorflow 模型與 Hugging Face Transformers 結合和訓練。我想保存每個時期的 val_accuracy 的最佳模型。我使用了“tensorflow checkpoint”,但我得到了錯誤。我如何保存每個時代的最佳模型在張量流中使用變壓器 bert 的時代?
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.initializers import TruncatedNormal
from tensorflow.keras.losses import CategoricalCrossentropy,BinaryCrossentropy
from tensorflow.keras.metrics import CategoricalAccuracy,BinaryAccuracy
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.utils import plot_model
from transformers import AutoTokenizer,TFBertModel
import tensorflow as tf
from tensorflow.keras.layers import Input, Dense
tokenizer = AutoTokenizer.from_pretrained('bert-large-uncased')
bert = TFBertModel.from_pretrained('bert-large-uncased')
max_len = max_length
input_ids = Input(shape=(max_len,), dtype=tf.int32, name="input_ids")
input_mask = Input(shape=(max_len,), dtype=tf.int32, name="attention_mask")
# embeddings = dbert_model(input_ids,attention_mask = input_mask)[0]
embeddings = bert(input_ids,attention_mask = input_mask)[1] #(0 is the last hidden states,1 means pooler_output)
# out = tf.keras.layers.GlobalMaxPool1D()(embeddings)
out = tf.keras.layers.Dropout(0.1)(embeddings)
out = Dense(128, activation='relu')(out)
out = tf.keras.layers.Dropout(0.1)(out)
out = Dense(32,activation = 'relu')(out)
y = Dense(1,activation = 'sigmoid')(out)
model = tf.keras.Model(inputs=[input_ids, input_mask], outputs=y)
model.layers[2].trainable = True
#model.save_weights('path/savefile')
如果您使用的是 tensorflow,那么您可以在下面創建回調,這將保存每個時期的模型。 filepath 是您要保存模型的目錄的路徑。 model 是編譯模型的名稱。 模型將以 epoch-validation loss.h5 格式保存
class model_per_epoch(keras.callbacks.Callback):
def __init__(self, model,filepath):
self.filepath=filepath
self.model=model
def on_epoch_end(self,epoch, logs=None):
v_loss=logs.get('val_loss')
name= str(epoch) +'-' + str(v_loss)[:str(v_loss).rfind('.')+3] + '.h5'
file_id=os.path.join(self.filepath, name)
self.model.save(file_id)
save_dir=r'c:\Temp\models'
callbacks=[model_per_epoch(model, save_dir)]
在 model.fit 中包含 callback=callbacks 。 確保您保存模型的目錄存在。 下面的代碼是更復雜的回調版本。 添加了一個附加參數 save_best_only。 如果設置為 True,則僅保存驗證損失最低的模型。 此外,模型加載了具有最低驗證損失的時期的權重,因此您可以直接使用模型進行預測,而無需加載保存的模型。 這可以節省大量時間。
class model_per_epoch(keras.callbacks.Callback):
def __init__(self, model,filepath,save_best_only):
self.filepath=filepath
self.model=model
self.save_best_only=save_best_only
self.lowest_loss=np.inf
self.best_weights=self.model.get_weights()
def on_epoch_end(self,epoch, logs=None):
v_loss=logs.get('val_loss')
if v_loss< self.lowest_loss:
self.lowest_loss =v_loss
self.best_weights=self.model.get_weights()
self.best_epoch=epoch +1
if self.save_best_only==False:
name= str(epoch) +'-' + str(v_loss)[:str(v_loss).rfind('.')+3] + '.h5'
file_id=os.path.join(self.filepath, name)
self.model.save(file_id)
def on_train_end(self, logs=None):
if self.save_best_only == True:
self.model.set_weights(self.best_weights)
name= str(self.best_epoch) +'-' + str(self.lowest_loss)[:str(self.lowest_loss).rfind('.')+3] + '.h5'
file_id=os.path.join(self.filepath, name)
self.model.save(file_id)
print(' model is returned with best weiights from epoch ', self.best_epoch)
save_dir=r'c:\Temp\models'
save_best_only= True
callbacks=[model_per_epoch(model, save_dir, save_best_only)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.