本博客是根据斯坦福大学的一门 tensorflow 课程的课件整理。这是课程地址 CS 20: Tensorflow for Deep Learning Research。
1 TensorBoard 使用简介
tensorboard
可以用来使你创建的图可视化,比如你创建了一个复杂的神经网络,复杂到自己都不太理解,这时候就可以用tensorboard
来看一看你的图,让你更好的去训练、调试或者优化。我们首先给出使用的方法,
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) print(sess.run(x)) writer.close()
如果你还记得上一节课写的程序,那你应该能注意到这里多了两行程序。想要使用
tensorboard
,就得先将你定义的图写到日志文件里,用法是:writer = tf.summary.FileWriter([logdir], [graph])
其中的
[logdir]
是你日志文件的目录。需要注意的一点是,在windows
系统上,你的目录路径要么是类似./graphs
这样在日志文件的上一层。要么拥有更长的路径,这时候你需要用双斜杠分开路径,比如E:\\TensorBoard\\logfile
.[graph]
是你想要查看的图,一般是你当前正在使用的。你可以使用tf.get_default_graph()
或者sess.graph
作为参数(当然你得先创建一个sess
才能这么写)。注意:上述的语句必须得写在你定义好图之后,执行计算之前。
接下来,运行的程序,并启动
tensorboard
,在命令行输入:python [filename.py] tensorboard --logdir="./graphs" --port 6006
[filename.py]
是你自己程序的名字,logdir=
后面也要改成你自己的目录,port
是可选的参数,tensorboard
默认的端口就是6006
.然后根据屏幕上的提示,在浏览器输入地址,就可以看到刚才创建的图了。
你还可以自定义上面节点的名字,将代码中的几行改成如下:
a = tf.constant(2, name="a") b = tf.constant(3, name="b") x = tf.add(a, b, name="add")
再运行
tensorboard
以后就会变成:注意:如果你重复运行程序,目录下会生成多个日志文件,需要自己手动清理一下。
现在你已经知道了怎么使用
tensorboard
,还有很多其他功能需要你自己去探索。
2 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")
可以创建一个特定维数的张量(tensor),然后填入特定的值:
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]]
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]]
tf.ones(shape, dtype=tf.float32, name=None) # create a tensor of shape and all elements are ones tf.ones([2, 3], tf.int32) ==> [[1, 1, 1], [1, 1, 1]]
tf.ones_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 ones. # input_tensor is [[0, 1], [2, 3], [4, 5]] tf.ones_like(input_tensor) ==> [[1, 1], [1, 1], [1, 1]]
tf.fill(dims, value, name=None) # create a tensor filled with a scalar value. tf.fill([2, 3], 8) ==> [[8, 8, 8