huseinzol05 / Stock-Prediction-Models

Gathers machine learning and deep learning models for Stock forecasting including trading bots and simulations
Apache License 2.0
7.66k stars 2.74k forks source link

How to export tf session/model after training #89

Open dougmbaya opened 3 years ago

dougmbaya commented 3 years ago

Instead of retraining the model every time. Is there a code to export a model such that it can be used for further inferences. Note that pickling doesn’t work with tf as it’s multithreaded and will have a lock. @huseinzol05

nil-andreu commented 1 year ago

@dougmbaya @huseinzol05 You can both save the model or save the weights. In the case we want to save the weights (less memory usage):

# Include the epoch in the file name (uses `str.format`)
checkpoint_path = "training/cp-{epoch:04d}.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)

# Create a callback that saves the model's weights every 5 epochs
cp_callback = tf.keras.callbacks.ModelCheckpoint(
    filepath=checkpoint_path, 
    verbose=1, 
    save_weights_only=True,
    save_freq=5*batch_size)

# Create a new model instance
model = create_model()

# Save the weights using the `checkpoint_path` format
model.save_weights(checkpoint_path.format(epoch=0))

# Train the model
model.fit(...)

# And we want to load the weights used
model = create_model()
model.load_weights(...)

For documentation here.