跳到主要内容

认识

2025年02月09日
柏拉文
越努力,越幸运

一、认识


TFJS 中,一个完整的模型通常包含:

  • model.json: 模型结构、权重路径等元数据(数据流图和权重清单文件)

  • group1-shard\*of\*: 二进制权重文件的集合

模型量化(Quantization: 模型量化是指将模型的权重和激活函数从浮点数(通常是32位浮点数)转换为较低精度的数值(如8位整数),以减少模型的大小和提高推理速度。通过 TensorFlow.js 支持的 模型量化(Quantization 技术,将模型大小压缩 50%-70%,降低推理计算负载。简单来讲, 模型量化(Quantization 就是牺牲一部分精度,来将模型压缩的更小。我们可以通过 tensorflowjs_converter 命令使用 --quantize_uint16 或者 --quantize_uint8 来对模型进行量化。

二、准备


1. 下载 tensorflow/tensorflow 镜像

docker pull --platform tensorflow/tensorflow:2.10.0

2. 运行 tensorflow/tensorflow 容器

docker run -it --rm tensorflow/tensorflow:2.10.0 bash

3. 安装 tensorflow==2.0.0 tensorflowjs

pip install tensorflow==2.0.0 tensorflowjs

4. 将本地模型发送到 Docker 容器

docker cp /path/to/my_model.h5 <container_id>:/tmp/layers_model/model.json

三、量化


model.json 的权重转换为精度较低的 16 位浮点数

tensorflowjs_converter \
--input_format tfjs_layers_model \
--output_format tfjs_layers_model \
--quantize_uint16 \
original_model/model.json
quantized_model/