Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Loaded Keras Model Throws Error While Predicting (Likely Issues with Masking) #20706

Open
JoeDoyle12 opened this issue Dec 31, 2024 · 1 comment

Comments

@JoeDoyle12
Copy link

I am currently developing and testing a RNN that relies upon a large amount of data for training, and so have attempted to separate my training and testing files. I have one file where I create, train, and save a tensorflow.keras model to a file 'model.keras' I then load this model in another file and predict some values, but get the following error: Failed to convert elements of {'class_name': 'tensor', 'config': {'dtype': 'float64', 'value': [0.0, 0.0, 0.0, 0.0]}} to Tensor. Consider casting elements to a supported type. See https://www.tensorflow.org/api_docs/python/tf/dtypes for supported TF dtypes

By the way, I have tried running model.predict with this exact same data in the file where I train the model, and it works smoothly. The model loading must be the problem, not the data used to predict.

This mysterious float64 tensor is the value I passed into the masking layer. I don't understand why keras is unable to recognize this JSON object as a Tensor and apply the masking operation as such. I have included snippets of my code below, edited for clarity and brevity:

model_generation.py:

# Create model

model = tf.keras.Sequential([
    tf.keras.layers.Input((352, 4)),
    tf.keras.layers.Masking(mask_value=tf.convert_to_tensor(np.array([0.0, 0.0, 0.0, 0.0]))),
    tf.keras.layers.GRU(50, return_sequences=True, activation='tanh'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.GRU(50,activation='tanh'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(units=1, activation='sigmoid')])

# Compile Model...
# Train Model...
model.save('model.keras')

model.predict(data) # Line works here

model_testing.py

model = tf.keras.models.load_model('model.keras')

model.predict(data) # this line generates the error

I have tried to re-load the model in the model_generation.py file and I get the exact same issue.

@dhantule
Copy link
Contributor

dhantule commented Jan 6, 2025

Hi @JoeDoyle12, thanks for reporting this. The error seems to be coming from the mask_value that you are trying to pass. If you try passing your like this mask_value=[0.0,0.0,0.0,0.0] , your code should work fine. Attaching gist

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants