forked from sony/model_optimization
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_keras_mobilenet.py
120 lines (95 loc) · 5.39 KB
/
example_keras_mobilenet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# Copyright 2021 Sony Semiconductor Israel, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import argparse
from tensorflow.keras.applications.mobilenet import MobileNet
import model_compression_toolkit as mct
import tempfile
"""
This tutorial demonstrates how a model (more specifically, MobileNetV1) can be
quantized and optimized using the Model Compression Toolkit (MCT).
"""
####################################
# Preprocessing images
####################################
import cv2
import numpy as np
MEAN = 127.5
STD = 127.5
RESIZE_SCALE = 256 / 224
SIZE = 224
def resize(x):
resize_side = max(RESIZE_SCALE * SIZE / x.shape[0], RESIZE_SCALE * SIZE / x.shape[1])
height_tag = int(np.round(resize_side * x.shape[0]))
width_tag = int(np.round(resize_side * x.shape[1]))
resized_img = cv2.resize(x, (width_tag, height_tag))
offset_height = int((height_tag - SIZE) / 2)
offset_width = int((width_tag - SIZE) / 2)
cropped_img = resized_img[offset_height:offset_height + SIZE, offset_width:offset_width + SIZE]
return cropped_img
def normalization(x):
return (x - MEAN) / STD
def argument_handler():
parser = argparse.ArgumentParser()
parser.add_argument('--representative_dataset_dir', type=str, required=True, default=None,
help='folder path for the representative dataset.')
parser.add_argument('--batch_size', type=int, default=50,
help='batch size for the representative data.')
parser.add_argument('--num_calibration_iterations', type=int, default=10,
help='number of iterations for calibration.')
return parser.parse_args()
if __name__ == '__main__':
# Parse arguments
args = argument_handler()
# Set the batch size of the images at each calibration iteration.
batch_size = args.batch_size
# Set the path to the folder of images to load and use for the representative dataset.
# Notice that the folder have to contain at least one image.
folder = args.representative_dataset_dir
# Create a representative data generator, which returns a list of images.
# The images can be preprocessed using a list of preprocessing functions.
image_data_loader = mct.core.FolderImageLoader(folder,
preprocessing=[resize, normalization],
batch_size=batch_size)
# Create a Callable representative dataset for calibration purposes.
# The function should be called without any arguments, and should return a list numpy arrays (array for each
# model's input).
# For example: A model has two input tensors - one with input shape of [32 X 32 X 3] and the second with
# an input shape of [224 X 224 X 3]. We calibrate the model using batches of 20 images.
# Calling representative_data_gen() should return a list
# of two numpy.ndarray objects where the arrays' shapes are [(20, 3, 32, 32), (20, 3, 224, 224)].
def representative_data_gen() -> list:
for _ in range(args.num_calibration_iterations):
yield [image_data_loader.sample()]
# Get a TargetPlatformModel object that models the hardware for the quantized model inference.
# The model determines the quantization methods to use during the MCT optimization process.
# Here, for example, we use the default target platform model that is attached to a Tensorflow
# layers representation.
target_platform_cap = mct.get_target_platform_capabilities('tensorflow', 'default')
# Create a model and quantize it using the representative_data_gen as the calibration images.
# Set the number of calibration iterations.
model = MobileNet()
quantized_model, quantization_info = mct.ptq.keras_post_training_quantization_experimental(model,
representative_data_gen,
target_platform_capabilities=target_platform_cap)
# Export quantized model to TFLite and Keras.
# For more details please see: https://github.com/sony/model_optimization/blob/main/model_compression_toolkit/exporter/README.md
_, tflite_file_path = tempfile.mkstemp('.tflite') # Path of exported model
mct.exporter.keras_export_model(model=quantized_model,
save_model_path=tflite_file_path,
serialization_format=mct.exporter.KerasExportSerializationFormat.TFLITE,
quantization_format=mct.exporter.QuantizationFormat.FAKELY_QUANT)
_, keras_file_path = tempfile.mkstemp('.h5') # Path of exported model
mct.exporter.keras_export_model(model=quantized_model,
save_model_path=keras_file_path)