NREL / polyID

https://polyid.nrel.gov
BSD 3-Clause "New" or "Revised" License
11 stars 3 forks source link

version of Keras and Tensorflow #6

Closed eefm1 closed 1 month ago

eefm1 commented 2 months ago

What version of Keras and Tensorflow did you use? Tensorflow=2.10 is mentioned in the environment file, but Keras is not.

With Keras 3 you have to save the model as .keras file instead as .h5, but doing so raises errors in loading the model later on. "Layer 'dense' was never built and thus it doesn't have any variables. However the weights file lists 2 variables for this layer. In most cases, this error indicates that either:

  1. The layer is owned by a parent layer that implements a build() method, but calling the parent's build() method did NOT create the state of the child layer 'dense'. A build() method must create ALL state for the layer, including the state of any children layers.

  2. You need to implement the def build_from_config(self, config) method on layer 'dense', to specify how to rebuild it during loading. In this case, you might also want to implement the method that generates the build config at saving time, def get_build_config(self). The method build_from_config() is meant to create the state of the layer (i.e. its variables) upon deserialization."

Probably the code was written using an older version of Keras, is that right? And what version should I use to avoid this error?

jlaw9 commented 2 months ago

Yes that's correct the code was written using Keras v2.10. In order to load the model, you have to specify the custom_objects as is done here.

For example:

from keras.models import load_model as load_keras_model
from nfp import (EdgeUpdate, GlobalUpdate, NodeUpdate,
                 masked_mean_absolute_error)

custom_objects_dict = {
    "GlobalUpdate": GlobalUpdate,
    "EdgeUpdate": EdgeUpdate,
    "NodeUpdate": NodeUpdate,
    "masked_mean_absolute_error": masked_mean_absolute_error,
}
model_fname = "example.h5"
model = load_keras_model(model_fname, custom_objects=custom_objects_dict)

I'll make a note to implement the build_from_config() for Keras 3 (pull requests also welcome :) ).

eefm1 commented 1 month ago

I've installed the aformementioned versions and now it works :-)