二、通过python训练一个tensorflow模型
用python训练一个tensorlfow模型不是本系列文章的重点,所以这里只训练一个简单的模型。
在某一目录下,新建demo.py,输入以下python代码,
import tensorflow as tf
import numpy as np
import os
tf.app.flags.DEFINE_integer('training_iteration', 1000,
'number of training iterations.')
tf.app.flags.DEFINE_integer('model_version', 1, 'version number of the model.')
tf.app.flags.DEFINE_string('work_dir', './', 'Working directory.')
FLAGS = tf.app.flags.FLAGS
x = tf.placeholder(tf.float32, shape=[None, 5], name="input")
y_ = tf.placeholder(tf.float32, shape=[None, 1])
w = tf.get_variable('w', shape=[5, 1], initializer=tf.truncated_narmal_initializer)
b = tf.get_variable('b', shape=[1], initializr=tf.zeros_initializer)
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
y = tf.add(tf.matmul(x,w), b, name="outputs")
loss = tf.reduce_mean((y-y_)**2)
train_step = tf.train.GradientDescentOptimizer(0.005).minimize(loss)
train_x = np.random.randn(1000, 5)
# let the model learn the equation of y = x1 * 1 + x2 * 2 + x3 * 3
train_y = np.sum(train_x * np.array([1, 2, 3,4,5]) + np.random.randn(1000, 5) / 100, axis=1).reshape(-1, 1)
for i in range(FLAGS.training_iteration):
loss, _ = sess.run([ms_loss, train_step], feed_dict={x: train_x, y_: train_y})
if i%100==0:
print("loss is:",loss)
graph = tf.graph_util.convert_variables_to_constants(sess, sess.graph_def, ["inputs", "outputs"])
tf.train.write_graph(graph, ".", FLAGS.work_dir + "liner.pb", as_text=False)
print('Done exporting!')
print('Done training!')
在当前目录运行:
python demo.py
运行完毕如果没有报错,则会在当前目录生成一个liner.pb文件。
注意:训练模型的时候最好给输入输出命名好,以上的输入命名为input,输出命名为outputs。这个在模型重加载的时候会用到。
三、模型参数固化
以上是通过python用tensorflow训练一个简单的模型,模型格式为pb格式。当然,你有可能已经有了tensorflow生成的四个模型文件,
checkpoint
models-0.data-00000-of-00001
models-0.index
models-0.meta
此时,你可以通过tensorflow提供的工具,把模型参数固化到*.pb文件中。
我们已经安装了bazel,现在只需要下载tensorflow源码,https://github.com/tensorflow/tensorflow
下好后解压,之后依次在ubuntu对应的源码目录tensorflow(不是在tensorflow/tensorflow下)下输入如下命令:
#编译build freeze_graph 工具
bazel build tensorflow/python/tools:freeze_graph
然后用这个工具进行模型固化:
bazel-bin/tensorflow/python/tools/freeze_graph --input_graph=你的模型目录/model.ckpt/ --output_node_names=output:0--output_graph=你要输出的目录/frozen.pb
四、模型量化压缩
为了将深度学习模型部署到移动设备上,如果我们的模型比较大,我们需要对模型进行压缩,减少模型的内存占用,缩短推断时间,减少耗电。模型压缩有很多方法,有兴趣的同行们可以看看这个博客https://blog.csdn.net/wspba/article/details/75671573
这里我们用tensorflow提供的量化工具进行模型压缩:
- 在tensorflow源码一级目录下(tensorflow):
#编译量化工具
bazel build tensorflow/tools/graph_transforms:transform_graph
- 量化我们的模型参数:
bazel-bin/tensorflow/tools/graph_transforms/transform_graph --in_graph=你们的模型目录/*.pb --outputs="outputs" --out_graph=你的输出模型目录/*.pb --transforms='quantize_weights'
做完量化后,你的模型大概会下降为原来的四分之一。
网友评论