I use Tensorflow for regression using the following function
import tensorflow as tf
def ff(*args, **kwargs):
model = tf.keras.models.Sequential()
model.add(tf.keras.Input(shape=[inp_train.shape[-1],]))
for i in range(n_layer):
model.add(tf.keras.layers.Dense(n_unit, activation=act))
model.add(tf.keras.layers.Dense(out_train.shape[1]))
model.compile(optimizer=opt, loss='mae')
early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=100)
check_point = tf.keras.callbacks.ModelCheckpoint('best_model.h5', monitor='val_loss', save_best_only=True)
model.fit(inp_train, out_train, epochs=n_epoch, batch_size=s_batch, validation_data=(inp_val, out_val), callbacks=[early_stop, check_point], verbose=0)
best_model = tf.keras.models.load_model('best_model.h5')
return model, best_mode
As you see, I save the best model by check_point callback and use it later for prediction. The problem is that in this way I have to save the best model on the disk first, and then load it from the disk. If I want to do a couple of runs in parallel, since each run create a file with the same name it does not work.
So, how can I assign the best model in a variable without having to save it on the disk?