首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >量化Keras神经网络模型

量化Keras神经网络模型
EN

Stack Overflow用户
提问于 2018-09-10 21:53:12
回答 2查看 6.7K关注 0票数 19

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

代码语言:javascript
复制
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) (该页面自2018年9月15日起不再提供)建议使用这段代码:

代码语言:javascript
复制
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创建的高级模型)。我不知道这个量化部分与之前创建的神经网络模型有什么关系。只要在神经网络代码后面插入它,就会遇到以下错误:

代码语言:javascript
复制
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模型中提取一些低级方法。

EN

回答 2

Stack Overflow用户

发布于 2019-08-12 22:46:57

由于你的网络看起来很简单,你可以使用Tensorflow lite

票数 1
EN

Stack Overflow用户

发布于 2019-08-22 21:48:46

Tensorflow lite可用于量化keras模型。

以下代码是为tensorflow 1.14编写的。它可能不适用于早期版本。

首先,在训练模型之后,您应该将模型保存到h5

代码语言:javascript
复制
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)
model.save("model.h5")

要加载keras模型,请使用tf.lite.TFLiteConverter.from_keras_model_file

代码语言:javascript
复制
# load the previously saved model
converter  = tf.lite.TFLiteConverter.from_keras_model_file("model.h5")
tflite_model = converter.convert()
# Save the model to file
with open("tflite_model.tflite", "wb") as output_file:
    output_file.write(tflite_model)

保存的模型可以加载到python脚本或其他平台和语言。为了使用保存的tflite模型,tensorlfow.lite提供了Interpreter。下面来自here的例子展示了如何使用python脚本从本地文件加载tflite模型。

代码语言:javascript
复制
import numpy as np
import tensorflow as tf

# Load TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter(model_path="tflite_model.tflite")
interpreter.allocate_tensors()

# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# Test model on random input data.
input_shape = input_details[0]['shape']
input_data = np.array(np.random.random_sample(input_shape), dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data)

interpreter.invoke()

# The function `get_tensor()` returns a copy of the tensor data.
# Use `tensor()` in order to get a pointer to the tensor.
output_data = interpreter.get_tensor(output_details[0]['index'])
print(output_data)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52259343

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档