
文章插图

文章插图
# -*- coding:utf-8 -*-# Author:凌逆战 | Never# Date: 2022/10/12"""整型量化"""import logging# 只显示bug不显示 warninglogging.getLogger("tensorflow").setLevel(logging.DEBUG)import tensorflow as tfimport numpy as np# 加载 MNIST 数据集mnist = tf.keras.datasets.mnist(train_images, train_labels), (test_images, test_labels) = mnist.load_data()# Normalize 输入图像,使每个像素值在0到1之间train_images = train_images.astype(np.float32) / 255.0test_images = test_images.astype(np.float32) / 255.0# 搭建模型结构model = tf.keras.Sequential([ tf.keras.layers.InputLayer(input_shape=(28, 28)), tf.keras.layers.Reshape(target_shape=(28, 28, 1)), tf.keras.layers.Conv2D(filters=12, kernel_size=(3, 3), activation='relu'), tf.keras.layers.MaxPooling2D(pool_size=(2, 2)), tf.keras.layers.Flatten(), tf.keras.layers.Dense(10)])model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])model.fit(train_images, train_labels, epochs=5, validation_data=https://www.huyubaike.com/biancheng/(test_images, test_labels))# 下面是一个没有量化的转换后模型 -------------------------------converter = tf.lite.TFLiteConverter.from_keras_model(model)tflite_model = converter.convert()# 下面是全整型量化 -----------------------------------------def representative_data_gen(): for input_value in tf.data.Dataset.from_tensor_slices(train_images).batch(1).take(100): # 模型只有一个输入,因此每个数据点有一个元素 yield [input_value]converter = tf.lite.TFLiteConverter.from_keras_model(model)converter.optimizations = [tf.lite.Optimize.DEFAULT] # 先启动默认的optimizations将模型权重进行量化converter.representative_dataset = representative_data_gen # 使用代表数据集量化模型中间值# 如果有任何的 ops不能量化,converter 将抛出错误converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]# 将输入和输出tensors设置为int8 类型converter.inference_input_type = tf.uint8 # or tf.int8converter.inference_output_type = tf.uint8 # or tf.int8tflite_model_quant = converter.convert()import pathlibtflite_models_dir = pathlib.Path("./mnist_tflite_models/")tflite_models_dir.mkdir(exist_ok=True, parents=True)# Save the unquantized/float model:tflite_model_file = tflite_models_dir / "mnist_model.tflite"tflite_model_file.write_bytes(tflite_model)# Save the quantized model:tflite_model_quant_file = tflite_models_dir / "mnist_model_quant.tflite"tflite_model_quant_file.write_bytes(tflite_model_quant)# 在TFLite模型上运行推理def run_tflite_model(tflite_file, test_image_indices): global test_images # 初始化 Interpreter interpreter = tf.lite.Interpreter(model_path=str(tflite_file)) interpreter.allocate_tensors() # 分配张量 input_details = interpreter.get_input_details()[0] # 输入 output_details = interpreter.get_output_details()[0] # 输出 predictions = np.zeros((len(test_image_indices),), dtype=int) for i, test_image_index in enumerate(test_image_indices): test_image = test_images[test_image_index] test_label = test_labels[test_image_index] # 检查输入类型是否被量化,然后将输入数据缩放到uint8 if input_details['dtype'] == np.uint8: input_scale, input_zero_point = input_details["quantization"] test_image = test_image / input_scale + input_zero_point test_image = np.expand_dims(test_image, axis=0).astype(input_details["dtype"]) interpreter.set_tensor(input_details["index"], test_image) interpreter.invoke() output = interpreter.get_tensor(output_details["index"])[0] predictions[i] = output.argmax() return predictions# 在所有图像上评估一个TFLite模型def evaluate_model(tflite_file, model_type): global test_images global test_labels test_image_indices = range(test_images.shape[0]) predictions = run_tflite_model(tflite_file, test_image_indices) accuracy = (np.sum(test_labels == predictions) * 100) / len(test_images) print('%s model accuracy is %.4f%% (Number of test samples=%d)' % ( model_type, accuracy, len(test_images)))evaluate_model(tflite_model_file, model_type="Float")# Float model accuracy is 97.7500% (Number of test samples=10000)evaluate_model(tflite_model_quant_file, model_type="Quantized")# Quantized model accuracy is 97.7000% (Number of test samples=10000)
经验总结扩展阅读
- 幼师好还是护士好 哪个更吃香
- 2023年2月6日是买衣服的黄道吉日吗 2023年2月6日买衣服黄道吉日
- 2023年2月6日适合制作寿衣吗 2023年2月6日是制作寿衣吉日吗
- 2023年2月6日买鸡黄道吉日 2023年2月6日买鸡行吗
- 2023年2月6日买牛好不好 2023年2月6日买牛吉日一览表
- 2023年2月6日画画好不好 2023年农历正月十六画画吉日
- 2023年10月1日入学行吗 2023年农历八月十七入学吉日
- 2023年10月1日是举办成人仪式的黄道吉日吗 2023年10月1日举办成人仪式吉日一览表
- 2023年10月1日上学好不好 2023年10月1日适合上学吗
- 2023年10月1日清扫房屋好吗 2023年农历八月十七宜清扫房屋吗