常量和变量
TensorFlow 中最基本的单位是常量(Constant)、变量(Variable)和占位符(Placeholder)。常量定义后值和维度不可变,变量定义后值可变而维度不可变。在神经网络中,变量一般可作为储存权重和其他信息的矩阵,而常量可作为储存超参数或其他结构信息的变量。下面我们分别定义了常量与变量:
-
a = tf.constant(2, tf.int16)
-
b = tf.constant(4, tf.float32)
-
c = tf.constant(8, tf.float32)
-
d = tf.Variable(2, tf.int16)
-
e = tf.Variable(4, tf.float32)
-
f = tf.Variable(8, tf.float32)
-
g = tf.constant(np.zeros(shape=(2,2), dtype=np.float32))
-
h = tf.zeros([11], tf.int16)
-
i = tf.ones([2,2], tf.float32)
-
j = tf.zeros([1000,4,3], tf.float64)
-
k = tf.Variable(tf.zeros([2,2], tf.float32))
-
l = tf.Variable(tf.zeros([5,6,5], tf.float32))
在上面代码中,我们分别声明了不同的常量(tf.constant())和变量(tf.Variable()),其中tf.float 和tf.int tftf分别声明了不同的浮点型和整数型数据。而 tf.ones() 和 tf.zeros() 分别产生全是 1、全是 0 的矩阵。我们注意到常量 g,它的声明结合了 TensorFlow 和 Numpy,这也是可执行的。
w1=tf.Variable(tf.random_normal([2,3],stddev=1,seed=1))
以上语句声明一个2 行 3 列的变量矩阵,该变量的值服从标准差为 1 的正态分布,并随机生成。
现在,我们可以应用变量来定义神经网络中的权重矩阵和偏置项向量:
-
weights = tf.Variable(tf.truncated_normal([256 * 256, 10]))
-
biases = tf.Variable(tf.zeros([10]))
-
print(weights.get_shape().as_list())
-
print(biases.get_shape().as_list())
-
#输出
-
>>>[65536, 10]
-
>>>[10]