tensorflow---之常量与变量的区别

常量和变量

TensorFlow 中最基本的单位是常量(Constant)、变量(Variable)和占位符(Placeholder)。常量定义后值和维度不可变,变量定义后值可变而维度不可变。在神经网络中,变量一般可作为储存权重和其他信息的矩阵,而常量可作为储存超参数或其他结构信息的变量。下面我们分别定义了常量与变量:

 
  1. a = tf.constant(2, tf.int16)

  2. b = tf.constant(4, tf.float32)

  3. c = tf.constant(8, tf.float32)

  4.  
  5. d = tf.Variable(2, tf.int16)

  6. e = tf.Variable(4, tf.float32)

  7. f = tf.Variable(8, tf.float32)

  8.  
  9. g = tf.constant(np.zeros(shape=(2,2), dtype=np.float32))

  10.  
  11. h = tf.zeros([11], tf.int16)

  12. i = tf.ones([2,2], tf.float32)

  13. j = tf.zeros([1000,4,3], tf.float64)

  14.  
  15. k = tf.Variable(tf.zeros([2,2], tf.float32))

  16. 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 的正态分布,并随机生成。

现在,我们可以应用变量来定义神经网络中的权重矩阵和偏置项向量:

 
  1. weights = tf.Variable(tf.truncated_normal([256 * 256, 10]))

  2. biases = tf.Variable(tf.zeros([10]))

  3. print(weights.get_shape().as_list())

  4. print(biases.get_shape().as_list())

  5. #输出

  6. >>>[65536, 10]

  7. >>>[10]

  1. 转载:https://blog.csdn.net/m0_37324740/article/details/77803590

猜你喜欢

转载自blog.csdn.net/zxyhhjs2017/article/details/82350903
今日推荐