量化Keras神经网络模型

sik*_*kr_ 16 python quantization neural-network keras tensorflow

最近,我开始使用Tensorflow + Keras创建神经网络,我想尝试Tensorflow中提供的量化功能.到目前为止,尝试TF教程的示例工作得很好,我有这个基本的工作示例(来自https://www.tensorflow.org/tutorials/keras/basic_classification):

import tensorflow as tf
from tensorflow import keras

fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

# fashion mnist data labels (indexes related to their respective labelling in the data set)
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

# preprocess the train and test images
train_images = train_images / 255.0
test_images = test_images / 255.0

# settings variables
input_shape = (train_images.shape[1], train_images.shape[2])

# create the model layers
model = keras.Sequential([
keras.layers.Flatten(input_shape=input_shape),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(10, activation=tf.nn.softmax)
])

# compile the model with added settings
model.compile(optimizer=tf.train.AdamOptimizer(),
          loss='sparse_categorical_crossentropy',
          metrics=['accuracy'])

# train the model
epochs = 3
model.fit(train_images, train_labels, epochs=epochs)

# evaluate the accuracy of model on test data
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:', test_acc)
Run Code Online (Sandbox Code Playgroud)

现在,我想在学习和分类过程中使用量化.量化文档(https://www.tensorflow.org/performance/quantization)(该页面自2018年9月15日cca以后不再可用)建议使用这段代码:

loss = tf.losses.get_total_loss()
tf.contrib.quantize.create_training_graph(quant_delay=2000000)
optimizer = tf.train.GradientDescentOptimizer(0.00001)
optimizer.minimize(loss)
Run Code Online (Sandbox Code Playgroud)

但是,它不包含有关应该使用此代码的位置或如何将其连接到TF代码的任何信息(甚至不提及使用Keras创建的高级模型).我不知道这个量化部分如何与先前创建的神经网络模型相关.只需在神经网络代码后插入它就会遇到以下错误:

Traceback (most recent call last):
  File "so.py", line 41, in <module>
    loss = tf.losses.get_total_loss()
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/losses/util.py", line 112, in get_total_loss
    return math_ops.add_n(losses, name=name)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/math_ops.py", line 2119, in add_n
    raise ValueError("inputs must be a list of at least one Tensor with the "
ValueError: inputs must be a list of at least one Tensor with the same dtype and shape
Run Code Online (Sandbox Code Playgroud)

是否可以量化以这种方式量化Keras NN模型,还是我遗漏了一些基本的东西?我想到的一个可能的解决方案可能是使用低级TF API而不是Keras(需要做很多工作来构建模型),或者尝试从Keras模型中提取一些较低级别的方法.

Jia*_*nyu 2

正如其他答案中提到的,TensorFlow Lite 可以帮助您进行网络量化。

TensorFlow Lite 提供多种级别的量化支持。

Tensorflow Lite 训练后量化可以轻松量化训练后的权重和激活。量化感知训练允许训练可以以最小的精度下降进行量化的网络;这仅适用于卷积神经网络架构的子集。

因此,首先,您需要决定是否需要训练后量化量化感知训练。例如,如果您已将模型保存为 *.h5 文件,您可能需要遵循 @Mitiku 的说明并进行训练后量化。

如果您希望通过模拟训练中量化的效果(使用您在问题中引用的方法)来获得更高的性能,并且您的模型位于量化感知训练支持的 CNN 架构的子集中,则此示例可能会在以下方面对您有所帮助Keras 和 TensorFlow 之间的交互。基本上,您只需要在模型定义及其拟合之间添加以下代码:

sess = tf.keras.backend.get_session()
tf.contrib.quantize.create_training_graph(sess.graph)
sess.run(tf.global_variables_initializer())
Run Code Online (Sandbox Code Playgroud)