Is there any way to detect the channels first or last format for TF saved model loaded as model=tf.saved_model.load(path)
?
In Keras and can go over model.layers
and check for a layer l l.data_format == 'channels_last'
Is there something like this for TF saved model? I can't find any suitable documentation of TF model details - everything goes back to Keras.
Channels First. We are aware of when the channel was last used and the manner in which kernels were applied, theoretically.
Channels first means that in a specific tensor (consider a photo), you would have (Number_Of_Channels, Height , Width) .
A SavedModel contains a complete TensorFlow program, including trained parameters (i.e, tf. Variable s) and computation. It does not require the original model building code to run, which makes it useful for sharing or deploying with TFLite, TensorFlow. js, TensorFlow Serving, or TensorFlow Hub.
In the tensorflow documentation for tf.saved_model.load it states:
"Keras models are trackable, so they can be saved to SavedModel. The object returned by tf.saved_model.load is not a Keras object (i.e. doesn't have .fit, .predict, etc. methods). A few attributes and functions are still available: .variables, .trainable_variables and .call."
I would suggest you try to extract the number of channels using the .variables attribute and then compare with the model architecture (I assume you have some rough knowledge what the input/output size is and how many channels there should be in the first layer)
# channel last format
input_shape = (32,32,3)
# build model in keras
model = keras.Sequential(
[
keras.layers.InputLayer(input_shape=input_shape),
layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),
layers.Flatten(),
layers.Dropout(0.5),
layers.Dense(2, activation="softmax"),
]
)
model.save('model')
Then load the model with tf
loaded_model = tf.saved_model.load('model')
and get the output shape of the first layer:
loaded_model.variables[0].shape
Output:
TensorShape([3, 3, 3, 32])
If we have knowledge about the model architecture and that the output of the first layer has 32 channels, it is now clear that the model is saved in channel last. However, if you have no knowledge about the model's structure it will probably be more tricky and this solution won't suffice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With