tf.keras HDF5 Model and Keras HDF5 Model - keras

I want to convert a Keras model to Tensorflow Lite model. When I examined the documentation, it is stated that we can use tf.keras HDF5 models as input. Does it mean I can use my saved HDF5 Keras model as input to it or tf.keras HDF5 model and Keras HDF5 models are different things?
Documentation: https://www.tensorflow.org/lite/convert
Edit: I could convert my Keras model to Tensorflow Lite model with using this API, but I didn't test it yet. My code:
converter = tf.lite.TFLiteConverter.from_keras_model_file(path + 'plant-
recognition-model.h5')
tflite_model = converter.convert()
with open('plant-recognition-model.tflite', 'wb') as f:
f.write(tflite_model)

tf.keras HDF5 model and Keras HDF5 models are not different things, except for inevitable software version update synchronicity. This is what the official docs say:
tf.keras is TensorFlow's implementation of the Keras API specification. This is a high-level API to build and train models that includes first-class support for TensorFlow-specific functionality
If the convertor can convert a keras model to tf.lite, it will deliver same results. But tf.lite functionality is more limited than tf.keras. If this feature set is not enough for you, you can still work with tensorflow, and enjoy its other advantages.
May be, it won't take too long before your models can run on a smartphone.

Related

convert tensorflow.keras model to keras model

I have an EfficientNet model (tensorflow.keras==2.4) and would like to use innvestigate to inspect the results, but it requires keras==2.2.4
Training code:
tensorflow.keras.__version__ # 2.4
model = tf.keras.applications.EfficientNetB1(**params)
# do training
model.save('testModel')
I have the model saved as file but can not load it into Keras 2.2.4. This is the point where I'm stuck, I couldn't figure out what to do to convert the model.
Use Innvestigate:
keras.__version__ # 2.2.4
keras.model.load_model('testModel') # Error
# some more stuff...
I also found this thread, might try it, but since efficient net has > 350 layers it is not really applicable
How to load tf.keras models with keras
I don't know if it's actually possible to convert models between tensorflow.keras and keras, I appreciate all help I can get.
Due to version incompatibility between tensorflow as keras, you were not able to load model.
Your issue will be resolved, once you upgrade keras and tensorflow to 2.5.

using keras h5 weights in tf.keras model

I have h5 weights from a Keras model.
I want to rewrite the Keras model into a tf.keras model (using TF2.x).
I know that only the high level API changed, but do you know if I still can use the h5 weights?
Most likely they can be loaded, but is the structure different between Keras and tf.keras weights?
Thanks
It seems that they are the same
cudos to Mohsin hasan answer
In the past, when I had to convert tf.keras model to keras model, I
did following:
Train model in tf.keras
Save only the weights tf_model.save_weights("tf_model.hdf5")
Make Keras model architecture using all layers in keras (same as the tf keras one)
load weights by layer names in keras: keras_model.load_weights(by_name=True)
This seemed to work for me. Since, I was using out of box architecture
(DenseNet169), I had to very less work to replicate tf.keras network
to keras.
And the answer from Alex Cohn
tf.keras HDF5 model and Keras HDF5 models are not different things,
except for inevitable software version update synchronicity. This is
what the official docs say:
tf.keras is TensorFlow's implementation of the Keras API specification. This is a high-level API to build and train models that
includes first-class support for TensorFlow-specific functionality
If the convertor can convert a keras model to tf.lite, it will deliver
same results. But tf.lite functionality is more limited than tf.keras.
If this feature set is not enough for you, you can still work with
tensorflow, and enjoy its other advantages.

loading pretrained (CNN) model from .ckpt file using Pytorch

I am using Pytorch for image classification. I am looking for CNN models pretrained on a dataset other than ImageNet, I have found a link to a ".ckpt" file. I also found tutorials on loading this file with Tenserflow, but not using pytorch.
How can I load pretrained model using Pytorch from ".ckpt" file ?
I agree with #jodag that in general, PyTorch and Tensorflow are not interoperable. There are some special cases in which you may be able to do this. For example, HuggingFace provides support for converting the transformer model from TensorFlow to PyTorch.
There is a related (though closed) question on DataScience StackExchange where the idea is to rewrite the Tensorflow model into PyTorch and then loads the weights from the checkpoint file. Note that this can get tricky at times.

Compatibility between keras and tf.keras models

I am interested in training a model in tf.keras and then loading it with keras. I know this is not highly-advised, but I am interested in using tf.keras to train the model because
tf.keras is easier to build input pipelines
I want to take advantage of the tf.dataset API
and I am interested in loading it with keras because
I want to use coreml to deploy the model to ios.
I want to use coremltools to convert my model to ios, and coreml tools only works with keras, not tf.keras.
I have run into a few road-blocks, because not all of the tf.keras layers can be loaded as keras layers. For instance, I've had no trouble with a simple DNN, since all of the Dense layer parameters are the same between tf.keras and keras. However, I have had trouble with RNN layers, because tf.keras has an argument time_major that keras does not have. My RNN layers have time_major=False, which is the same behavior as keras, but keras sequential layers do not have this argument.
My solution right now is to save the tf.keras model in a json file (for the model structure) and delete the parts of the layers that keras does not support, and also save an h5 file (for the weights), like so:
model = # model trained with tf.keras
# save json
model_json = model.to_json()
with open('path_to_model_json.json', 'w') as json_file:
json_ = json.loads(model_json)
layers = json_['config']['layers']
for layer in layers:
if layer['class_name'] == 'SimpleRNN':
del layer['config']['time_major']
json.dump(json_, json_file)
# save weights
model.save_weights('path_to_my_weights.h5')
Then, I use the coremlconverter tool to convert from keras to coreml, like so:
with CustomObjectScope({'GlorotUniform': glorot_uniform()}):
coreml_model = coremltools.converters.keras.convert(
model=('path_to_model_json','path_to_my_weights.h5'),
input_names=#inputs,
output_names=#outputs,
class_labels = #labels,
custom_conversion_functions = { "GlorotUniform": tf.keras.initializers.glorot_uniform
}
)
coreml_model.save('my_core_ml_model.mlmodel')
My solution appears to be working, but I am wondering if there is a better approach? Or, is there imminent danger in this approach? For instance, is there a better way to convert tf.keras models to coreml? Or is there a better way to convert tf.keras models to keras? Or is there a better approach that I haven't thought of?
Any advice on the matter would be greatly appreciated :)
Your approach seems good to me!
In the past, when I had to convert tf.keras model to keras model, I did following:
Train model in tf.keras
Save only the weights tf_model.save_weights("tf_model.hdf5")
Make Keras model architecture using all layers in keras (same as the tf keras one)
load weights by layer names in keras: keras_model.load_weights(by_name=True)
This seemed to work for me. Since, I was using out of box architecture (DenseNet169), I had to very less work to replicate tf.keras network to keras.

How can I use pytorch pre-trained model without installing pytorch?

I only want to use pre-trained model in pytorch without installing the whole package.
Can I just copy the model module from pytorch?
I'm afraid you cannot do that: in order to run the model, you need not only the trained weights ('.pth.tar' file) but also the "structure" of the net: that is, the layers, how they are connected to each other etc. This network structure is coded in python and requires pytorch to be installed.
A way of using PyTorch models without Installing PyTorch is if the model is exported in Onnx format. Once the model is in Onnx format the model can be Imported into the Onnx runtime and ca be used for Inferencing. This tutorial should help you out.Pytorch ONNX

Resources