TensorFlow之Variable

Creating a Variable:

《TensorFlow之Variable》
《TensorFlow之Variable》

通过参数指定变量名,shape,datatype,initializer(初始化方式)。

Variable collections:

collections:lists of tensors or other objects.

默认情况下,tf.Variable 会被放在以下两个collections中:

《TensorFlow之Variable》
《TensorFlow之Variable》

如果不想变量被改变,可以将其存放在tf.GraphKeys.LOCAL_VARIABLES.有以下两种方式:

《TensorFlow之Variable》
《TensorFlow之Variable》

也可以创建自己的collection,任何字符串都可以作为collection名。

《TensorFlow之Variable》
《TensorFlow之Variable》

检索存储在collection中的变量,可以调用以下方法:

《TensorFlow之Variable》

Device placement:

可以选择将变量存储在某一设备上:

《TensorFlow之Variable》

在分布式系统中,如果将相关的变量放在不同的设备,会大大降低运算的速度。所以,推荐使用tf.train.replica_device_setter,他可以自动将参数置于参数服务器中:

《TensorFlow之Variable》
《TensorFlow之Variable》

Initializing variables:

在使用变量之前,必须要先进行初始化。显示初始化的优势在于,加载一个已经训练过的模型时,不必重新对其初始化。以下程序将会对tf.GraphKeys.GLOBAL_VARIABLES collection中的所有变量进行初始化:

《TensorFlow之Variable》
《TensorFlow之Variable》

如果需要初始化自己的变量:

《TensorFlow之Variable》

如果想要知道当前哪些变量未被初始化:将会打印出为初始化的变量名

《TensorFlow之Variable》
《TensorFlow之Variable》

初始化的顺序是随机地,如果某些变量的初始化值依赖于另一些变量的初始化值,很有可能会出错,因此我们建议使用以下方法:使用变量的值,而非变量本身

《TensorFlow之Variable》
《TensorFlow之Variable》

Using variable:

如果直接使用变量的值,可以用+-之类的符号进行,变量会在运算时,自动变成tensor,再进行运算。

《TensorFlow之Variable》
《TensorFlow之Variable》

如果要将变量值赋值给另一个变量,要使用assign()和assign_add()。

《TensorFlow之Variable》
《TensorFlow之Variable》

若要强制读取变量的值:

《TensorFlow之Variable》
《TensorFlow之Variable》

Sharing variables:

TensorFlow支持两种方式的变量共享:显式传递,使用tf.variable_scope对象将tf.Variable进行隐式包装

《TensorFlow之Variable》
《TensorFlow之Variable》

可以使用Variable scopes来对变量进行管理,见下面例子:

《TensorFlow之Variable》
《TensorFlow之Variable》

《TensorFlow之Variable》
《TensorFlow之Variable》

由于程序不清楚在第二次调用conv_relu函数是新建weights和biases变量,还是使用已经存在的这两个变量,所以报错:

《TensorFlow之Variable》
《TensorFlow之Variable》

如果要复用变量,有两种方法。创建相同名字的scope,并且reuse = true:

《TensorFlow之Variable》

《TensorFlow之Variable》

或者:

《TensorFlow之Variable》

    原文作者:motto
    原文地址: https://zhuanlan.zhihu.com/p/35608413
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞