本文的主要内容安排如下:
- 基本的操作
- 张量类型
- 导入数据
- lazy loading
我们首先介绍一下TensorBoard的使用,然后介绍TensorFlow的基本ops,之后介绍张量的数据类型,最后介绍一下如何将自己的输入导入模型。
1. TensorBoard
TensorBoard是TensorFlow的一个可视化工具,可以用于对TensorFlow模型的调试和优化。TensorBoard的外观大致如下:
当用户在TensorBoard激活的TensorFlow程序中执行某些操作时,这些操作将导出到事件日志文件中。 TensorBoard能够将这些事件文件转换为可视化文件,从而可以深入了解模型的结构及其运行时的行为。
让我们从一个小例子中,看看TensorBoard如何使用。下面的代码是不使用TensorBoard的计算a+b的例子:
import tensorflow as tf
a = tf.constant(2)
b = tf.constant(3)
x = tf.add(a, b)
with tf.Session() as sess:
print(sess.run(x))
为了使用TensorBoard对程序进行可视化,我们需要将模型写入日志文件中。而日志文件的写入,需要依赖于一个filewriter,其生命代码如下:
writer = tf.summary.FileWriter([logdir], [graph])
[graph]
指当前模型的运算图。可以使用tf.get_default_graph()
获取模型的默认运算图,或者使用sess.graph
获取当前会话处理的运算图;后者要求sess会话已经被声明。值得注意的是,FileWriter的声明需要放在在运算图定义完成之后,否则TensorBoard对模型的结构显示不完整。
[logdir]
表明日志文件的存储位置。可以将[logdir]
命名为’./graphs’或者’./graphs/lecture02’.
import tensorflow as tf
a = tf.constant(2)
b = tf.constant(3)
x = tf.add(a, b)
writer = tf.summary.FileWriter('./graphs', tf.get_default_graph())
with tf.Session() as sess:
# writer = tf.summary.FileWriter('./graphs', sess.graph) # if you prefer creating your writer using session's graph
print(sess.run(x))
writer.close()
模型运行之后会将日志文件写入并存储到指定位置。接下来,到命令行窗口,运行如下代码:
$ python3 [my_program.py]
$ tensorboard --logdir="./graphs" --port 6006
如果运行报错:OSError:[Errno 22] Invalid argument,解决方法为:clickME
运行成果后,在浏览器中打开网址:http://localhost:6006就可以看到TensorBoard页面了。你可以看到运算图中有3个结点:2个constants和一个Add op。
其中Const、Const_1分别对应结点a和结点b,Add对应x。我们也可以自己对结点命名:
a = tf.constant(2, name="a")
b = tf.constant(3, name="b")
x = tf.add(a, b, name="add")
再次运行打开TensorBoard后,我们可以得到:
运算图定义了ops以及它们的依赖关系。我们可以通过点击结点来确定结点的值以及结点类型。
在了解TensorBoard之后,我们来看看TensorFlow中的各种op。
2. Constant op
TensorFlow中创建常量constant的方式很简单。
tf.constant(value, dtype=None, shape=None, name='Const', verify_shape=False)
# constant of 1d tensor(vector)
a = tf.constant([2, 2], name="vector")
# constant of 2x2 tensor (matrix)
b = tf.constant([[0, 1], [2, 3]], name="matrix")
你也可以创建特定维度、填充特定值的常量,具体操作和使用Numpy类似。
# 创建任意维度,内部元素全是0的constant常量
tf.zeros(shape, dtype=tf.float32, name=None)
# create a tensor of shape and all elements are zeros
tf.zeros([2,3], tf.int32) ==> [[0, 0, 0], [0, 0, 0]]
# 创建和input_tensor维度相同,全是0的常量
tf.zeros_like(input_tensor, dtype=None, name=None, optimize=True)
# create a tensor of shape and type (unless type is specified) as the input_tensor but all
elements are zeros.
# input_tensor [[0, 1], [2, 3], [4, 5]]
tf.zeros_like(input_tensor) ==> [[0, 0], [0, 0], [0, 0]]
# 创建任意维度,值全是1的常量
tf.ones(shape, dtype=tf.float32, name=None)
# create a tensor of shape and all elements are ones
tf.ones([2, 3], tf.int32)