问题
I have some neural networks for the classification of images developed in Python 3.7 using the Keras package that is included in TensorFlow and I want to export the layers and weights model to import it in a Node.js application that uses Tensorflow.js.
I have the neural networks saved in h5 format with two separate files, one for the layer model and the other for the weights model. Try to follow this tutorial that Tensorflow proposes (https://www.tensorflow.org/js/tutorials/conversion/import_keras), but it does not work.
from tensorflow.python.keras.models import load_model
import numpy as np
import tensorflowjs as tf
import json
cnn_name = '1'
layers = './model/' + cnn_name + '/model.h5'
weights = './model/' + cnn_name + '/weights.h5'
cnn = load_model(layers)
cnn.load_weights(weights)
tf.converters.save_keras_model(cnn, './model/' + cnn_name + 'json/')
with open('./model/' + cnn_name + 'json/weights.json', 'w') as f:
json.dump(tf.converters.keras_h5_conversion.h5_weights_to_tfjs_format(weights), f, cls=NumpyEncoder)
In Node I can load the layer file using the function tf.loadLayersModel and start the model, but I can not load the weight file. I think I have to use the loadWeights method of the model that returns the loadLayersModel function, but you have to pass a weight manifest and I do not know how to get it.
回答1:
tf.loadLayersModel
loads the topology (model.json) and the weights file. The name of the weights file are in model.json file. However, if the weights files to be loaded are in a different folder, the property weightPathPrefix
of the options passed as parameter can be used. It will look like as the following:
tf.loadLayersModel(url, {weightPathPrefix: weightFolderPath});
来源:https://stackoverflow.com/questions/56915464/import-python-keras-model-with-weights-into-tensorflow-js