问题
I'm trying to save and load my keras model. It trains, evaluates, and saves fine (using .h5 to save model) but when I try to load the model I get the following error: ValueError: Input 0 is incompatible with layer flatten: expected min_ndim=3, found ndim=2. Am I loading the model incorrectly? Any help would be appreciated!
This is the code block from where I'm saving the model.
def ml(self):
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten())
self.addLayer(model,145,6)
model.add(tf.keras.layers.Dense(1))
optimizer = tf.keras.optimizers.Adam()
model.compile(loss='mean_squared_error',
optimizer=optimizer,
metrics=['mean_absolute_error',
'mean_squared_error'])
model.fit(self.x_train, self.y_train,epochs=130)
lm = model.evaluate(self.x_test, self.y_test, batch_size=300)
model.save('my_model.h5')
def addLayer(self, model, numNodes, numLayers):
for i in range(numLayers):
model.add(tf.keras.layers.Dense(numNodes,activation=tf.nn.relu))
To load from a different script:
import keras
from keras.models import load_model
from keras.utils import CustomObjectScope
from keras.initializers import glorot_uniform
with CustomObjectScope({'GlorotUniform': glorot_uniform()}):
model = load_model(mlPath)
While attempting to load the model I get the following error:
ValueError: Input 0 is incompatible with layer flatten: expected min_ndim=3, found ndim=2
回答1:
you can try to save only the weights of your model, then re-create it using exactly the same code, and loading only the weights. so change
model.save
to
model.save_weights('my_model.h5')
Then when you want to load your model, first, you re-create your model:
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten())
self.addLayer(model,145,6)
model.add(tf.keras.layers.Dense(1))
and finally load the weights:
model.load_weights('my_model.h5')
This worked for me. Also, you could add an Input layer, together with the explicit input_shape in your model.
来源:https://stackoverflow.com/questions/56859738/how-to-fix-valueerror-input-0-is-incompatible-with-layer-flatten-expected-mi