Converting the TensorFlow model into the Core ML model

The TensorFlow team has developed a package that is used to convert the models created in TensorFlow into Core ML, which in through is used in iOS apps. To use this, you must have macOS with Python 3.6 and TensorFlow installed. Using this, we can convert the TensorFlow model file (.pb) into the Core ML format (.mlmodel). First, you need to execute the following command:

Pip install tfcoreml

Once this is installed, write the following code in your Python file, name it inspect.py, and save it:

import tensorflow as tf
from tensorflow.core.framework import graph_pb2
import time
import operator
import sys

def inspect(model_pb, output_txt_file):
graph_def = graph_pb2.GraphDef()
with open(model_pb, "rb") as f:
graph_def.ParseFromString(f.read())

tf.import_graph_def(graph_def)

sess = tf.Session()
OPS = sess.graph.get_operations()

ops_dict = {}

sys.stdout = open(output_txt_file, 'w')
for i, op in enumerate(OPS):
print('---------------------------------------------------------------------------------------------------------------------------------------------')
print("{}: op name = {}, op type = ( {} ), inputs = {}, outputs = {}".format(i, op.name, op.type, ", ".join([x.name for x in op.inputs]), ", ".join([x.name for x in op.outputs])))
print('@input shapes:')
for x in op.inputs:
print("name = {} : {}".format(x.name, x.get_shape()))
print('@output shapes:')
for x in op.outputs:
print("name = {} : {}".format(x.name, x.get_shape()))
if op.type in ops_dict:
ops_dict[op.type] += 1
else:
ops_dict[op.type] = 1

print('---------------------------------------------------------------------------------------------------------------------------------------------')
sorted_ops_count = sorted(ops_dict.items(), key=operator.itemgetter(1))
print('OPS counts:')
for i in sorted_ops_count:
print("{} : {}".format(i[0], i[1]))

if __name__ == "__main__":
"""
Write a summary of the frozen TF graph to a text file.
Summary includes op name, type, input and output names and shapes.

Arguments
----------
- path to the frozen .pb graph
- path to the output .txt file where the summary is written

Usage
----------
python inspect_pb.py frozen.pb text_file.txt

"""
if len(sys.argv) != 3:
raise ValueError("Script expects two arguments. " +
"Usage: python inspect_pb.py /path/to/the/frozen.pb /path/to/the/output/text/file.txt")
inspect(sys.argv[1], sys.argv[2])

The preceding code will take the model file as an input argument, and save all the operations and input/output node names with a description in a text file that we supply as input. To run this, enter the following command:

Python inspect.py retrained_graph.pb summeries.txt

In this command, you are executing the inspect.py code you saved before. This will also input the graph file obtained from the previous section and, path of a text file where you want to save the summaries.

Once you execute this command, summeries.txt will be created with all the summaries, as shown here. These will be added into that file:

In this file, you can see all the operations, input and output names, and their shapes; you can also see the overall operators:

Toward the end of the file, you will find the definition of the end node; in our case, it is as follows:

Here, you can see that the end node operation type is Softmax, and the output that it will produce will be stored in the final_result:0 name. Now, check out the following code block, which is used to generate a corresponding Core ML model:

Let's understand the previous code block in detail. You must have noticed that we imported the tfcoreml package in the first line, and then used its convert function. The following are its arguments:

  • Tf_model_path: The (.pb) file path that you generated in the previous section, Converting the TensorFlow model into the Core ML model.
  • Mlmodel_path: The output model file path where you want to generate the model.
  • Output_feature_names: In this, we will get the output variable name that you obtained from the previous text file that was generated by our model-inspection code.
  • Image_input_names: Name you want to give for the image input. In Core ML/iOS, this will be the image buffer.
  • Class_labels: This is the file you will get in the training step.

Once you run the preceding code, you will see the generated converted.mlmodel file in your directory. You can import this into your Xcode project and make use of it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset