【发布时间】:2018-09-10 13:53:11
【问题描述】:
最近,我开始使用 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)
现在,我想在学习和分类过程中使用量化。量化文档 (https://www.tensorflow.org/performance/quantization)(该页面自 cca 2018 年 9 月 15 日起不再可用)建议使用这段代码:
loss = tf.losses.get_total_loss()
tf.contrib.quantize.create_training_graph(quant_delay=2000000)
optimizer = tf.train.GradientDescentOptimizer(0.00001)
optimizer.minimize(loss)
但是,它不包含有关应在何处使用此代码或应如何将其连接到 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
是否有可能以这种方式量化 Keras NN 模型,还是我缺少一些基本的东西? 我想到的一个可能的解决方案是使用低级 TF API 而不是 Keras(需要做很多工作来构建模型),或者尝试从 Keras 模型中提取一些低级方法。
【问题讨论】:
-
有什么新的更新吗?我也有同样的问题。
-
我根据colab.research.google.com/github/tensorflow/tensorflow/blob/… 进行了学习后量化工作,我很快就会在这里发布一个完整的工作示例。不过,量化意识训练还没有成功。
标签: python tensorflow neural-network keras quantization