Hello QuantConnect Community,
I am experiencing difficulties loading a TensorFlow model (.h5) from the Object Store into my QuantConnect algorithm. Here are the details:
Background:
- I have developed a stock trading algorithm using LSTM.
- The model is trained locally using TensorFlow and saved as a `.h5` file.
- The model file is uploaded to the QuantConnect Object Store.
**Problem:**
- When attempting to load the model within my QuantConnect algorithm, I encounter issues.
- It seems related to TensorFlow's handling of the `.h5` format within the QuantConnect environment.
**What I've Tried:**
- I attempted to use AWS S3 and Google Cloud Storage, but faced connectivity and access issues.
- The most efficient way seems to be using the QuantConnect Object Store, but the current method does not work.
**Code Snippet for Loading Model:**
```python
from AlgorithmImports import *
import tensorflow as tf
import os
class LSTMStockPredictionAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2020, 1, 1)
self.SetEndDate(2023, 1, 1)
self.SetCash(100000)
self.symbol = self.AddEquity("JBLU", Resolution.Daily).Symbol
self.look_back = 60
self.model_file_name = "JBLU_lstm_stock_model.h5"
self.model_path = f"/tmp/{self.model_file_name}"
# Attempt to download and load model from Object Store
self.DownloadModelFromObjectStore()
# Load the model
self.model = tf.keras.models.load_model(self.model_path)
def DownloadModelFromObjectStore(self):
if not self.ObjectStore.ContainsKey(self.model_file_name):
raise Exception(f"Model file {self.model_file_name} not found in Object Store")
model_bytes = self.ObjectStore.ReadBytes(self.model_file_name)
with open(self.model_path, 'wb') as f:
f.write(model_bytes)
self.Debug(f"Model downloaded from Object Store and saved to {self.model_path}")
def OnData(self, data):
pass # Implementation for trading logic
```
**Request:**
- Any guidance or troubleshooting tips on how to successfully load a TensorFlow `.h5` model from the Object Store would be greatly appreciated.
Thank you!
Mia Alissi
Hello Adam,
It seems like you're encountering an issue with loading a TensorFlow model from the Object Store in QuantConnect. This could be due to the way TensorFlow handles
.h5
files in the QuantConnect environment.One possible solution is to save and load your model weights in JSON format instead of
.h5
. This approach has been used successfully in the QuantConnect community. Here's an example of how you can do this:In this example,
NumpyArrayEncoder
is a custom JSON encoder for numpy arrays:Another approach is to serialize the TensorFlow graph and weights to JSON format, then save these in the ObjectStore by using the
Save
method. Here's an example of how you can do this:You can then load the model from the Object Store in your algorithm:
Please note that you need to have storage create permissions to save data in the Object Store if you run algorithms in QuantConnect Cloud.
I hope this helps! Let me know if you have any other questions.
Sources:
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
Adam Hanafi
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!