<jupyter_start><jupyter_text>Load all the Python Libraries Required<jupyter_code>import tensorflow as tf
from tensorflow.keras.layers import Input
from keras.applications.resnet50 import ResNet50
import keras.backend as K
from tensorflow.python.framework import graph_util, graph_io
import coremltools<jupyter_output>Using TensorFlow backend.
WARNING:root:TensorFlow version 1.12.0 detected. Last version known to be fully compatible is 1.5.0 .<jupyter_text>Set the learning phase using the backend as False and load the model<jupyter_code>K.set_learning_phase(False)

# Load the model with the weights trained on Imagenet 
model = ResNet50(weights='imagenet',include_top=True)<jupyter_output><empty_output><jupyter_text>Convert the model into a coreml model<jupyter_code># Convert the loaded Keras model into a CoreML Model
# Provide image_input_names to specify it is an image model
# also provide the bias values specified by the model
mlmodel = coremltools.converters.keras.convert(model, 
                                               input_names=['image'], 
                                               image_input_names=['image'],
                                               output_names=['classLabelProbs', 'classLabel'],
                                               class_labels='labels.txt', 
                                               blue_bias=-123.68,
                                               green_bias=-116.779,
                                               red_bias=-103.939)<jupyter_output>Output name length mismatch
0 : input_1, <keras.engine.topology.InputLayer object at 0xb2b5568d0>
1 : conv1_pad, <keras.layers.convolutional.ZeroPadding2D object at 0xd2babccc0>
2 : conv1, <keras.layers.convolutional.Conv2D object at 0xd2babca90>
3 : bn_conv1, <keras.layers.normalization.BatchNormalization object at 0xd2babceb8>
4 : activation_1, <keras.layers.core.Activation object at 0xd2babcf28>
5 : max_pooling2d_1, <keras.layers.pooling.MaxPooling2D object at 0x10bf78cf8>
6 : res2a_branch2a, <keras.layers.convolutional.Conv2D object at 0xd2bae4630>
7 : bn2a_branch2a, <keras.layers.normalization.BatchNormalization object at 0xd2bb78828>
8 : activation_2, <keras.layers.core.Activation object at 0xd2bc0c588>
9 : res2a_branch2b, <keras.layers.convolutional.Conv2D object at 0xd2bc38358>
10 : bn2a_branch2b, <keras.layers.normalization.BatchNormalization object at 0xd2bc38400>
11 : activation_3, <keras.layers.core.Activation object at 0xd2bc78f98>
12 : res2a_branch2c, <keras.layers.convol[...]<jupyter_text>Save the model as a .mlmodel file which can be deployed<jupyter_code>mlmodel.save('ModelZoo/ResNet50.mlmodel')<jupyter_output><empty_output><jupyter_text>Now extract the model using the TensorFlow session to convert it for Android<jupyter_code>S = K.get_session()
constant_graph = graph_util.convert_variables_to_constants(S, 
                                                           S.graph.as_graph_def(),
                                                           ['fc1000/Softmax'])
graph_io.write_graph(constant_graph, 'ModelZoo/', 'ResNet50.pb', as_text=False)<jupyter_output>INFO:tensorflow:Froze 320 variables.<jupyter_text>To convert the model for TensorFlow Lite<jupyter_code># To convert the model for tensorflow lite, we can save the keras model
# and then convert it into a TensorFlow lite model directly

input_tensor = tf.keras.layers.Input(shape=(224,224,3))
model = tf.keras.applications.resnet50.ResNet50(
    weights='imagenet', input_tensor=input_tensor, include_top=True
)

keras_file = 'ModelZoo/ResNet50.h5'
tf.keras.models.save_model(model, keras_file)

converter = tf.contrib.lite.TFLiteConverter.from_keras_model_file(keras_file)
tflite_model = converter.convert()
open('ModelZoo/'+'ResNet50.tflite', 'wb').write(tflite_model)<jupyter_output>WARNING:tensorflow:No training configuration found in save file: the model was *not* compiled. Compile it manually.<jupyter_text>Now load the model and get the details of the converted model These are useful when deploying the models on Android<jupyter_code>interpreter = tf.contrib.lite.Interpreter(model_path='ModelZoo/ResNet50.tflite')

interpreter.allocate_tensors()

input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
print(input_details, output_details)<jupyter_output>[{'name': 'input_1', 'index': 79, 'shape': array([  1, 224, 224,   3], dtype=int32), 'dtype': <class 'numpy.float32'>, 'quantization': (0.0, 0)}] [{'name': 'fc1000/Softmax', 'index': 77, 'shape': array([   1, 1000], dtype=int32), 'dtype': <class 'numpy.float32'>, 'quantization': (0.0, 0)}]
{'fraction_non_alphanumeric': 0.09574238167279014, 'fraction_numerical': 0.043440674303004106, 'mean_word_length': 3.8664563617245005, 'pattern_counts': {'":': 0, '<': 39, '<?xml version=': 0, '>': 38, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 18, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '342822', 'license': 'MIT', 'n_tokens_mistral': 1559, 'n_tokens_neox': 1451, 'n_words': 340, 'path': 'Model Conversion/ResNet50_Converter.ipynb', 'repo_name': 'abhishek-sehgal/Deep-Learning-Mobile', 'size': '4627'}