cppflow icon indicating copy to clipboard operation
cppflow copied to clipboard

How to extract weights from saved model?

Open abucka opened this issue 5 years ago • 2 comments

Hi!

How can I extract weights from the saved model?

I am looking for the equivalent of Python model.get_weights() but in Tensorflow C API. Especially, I would like to extract the weights for the last convolutional layer.

Thank you!

abucka avatar Dec 06 '20 20:12 abucka

Hi @abucka ,

Sorry for the late reply. I have been looking for this in the C API and in tf.raw_ops and I didn't find how. Please, if you figured it out, could you please send how? It would be nice to include it on cppflow.

Thanks and sorry

serizba avatar Feb 23 '21 10:02 serizba

Hi @serizba,

Yes, I finally figured it out.

Based on the c_api_experimental.h:

std::string checkpoint_path = path_to_model + "/variables/variables";  //path_to_model must be absolute path
const char * c = checkpoint_path.c_str();
TF_CheckpointReader* reader = TF_NewCheckpointReader(c, cppflow::context::get_status());
TF_Tensor* weights = TF_CheckpointReaderGetTensor(reader, "layer_with_weights-106/kernel/.ATTRIBUTES/VARIABLE_VALUE", cppflow::context::get_status());  // Second argument determines the layer with weights (the name can be determined in Python)
TF_DeleteCheckpointReader(reader);
cppflow::tensor w_tensor = cppflow::tensor(weights);

abucka avatar Apr 21 '21 13:04 abucka

Glad that you found out how to achieve this!

serizba avatar Sep 23 '22 11:09 serizba