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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值