tensorflow(二):变量Variable

1. 创建变量的方式:tf.Variable() 和 tf.placeholder()

 建议用tf.Variable() 和 tf.constant() 来初始化权重&偏置项。

       tf.Variable() 的使用小例:以0为初始值,每次加1,迭代循环3次;

state = tf.Variable(0)  
new_value = tf.add(state, tf.constant(1))
update = tf.assign(state, new_value)  

with tf.Session() as sess: 
    sess.run(tf.global_variables_initializer())
    print(sess.run(state))    
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))

2. 保存当前的session,用.Saver.save()

在模型保存时,直接保存session;可以每个几个epoch就保存一次模型

#tf.train.Saver
w = tf.Variable([[0.5,1.0]])
x = tf.Variable([[2.0],[1.0]])
y = tf.matmul(w, x)
init_op = tf.global_variables_initializer()
saver = tf.train.Saver()
with tf.Session() as sess:
    sess.run(init_op)
# Do some work with the model.
# Save the variables to disk.
    save_path = saver.save(sess, "C://tensorflow//model//test")
    print ("Model saved in file: ", save_path)

3. 把ndarray格式转为 tensorfow格式:用tf.convert_to_tensor()

import numpy as np
a = np.zeros((3,3))
ta = tf.convert_to_tensor(a)
with tf.Session() as sess:
     print(sess.run(ta))

4.  tf.placeholder() :仅作为一种占位符

tf.placeholder(dtype, shape=None, name=None)  

  • 此函数可以理解为形参,用于定义过程,在执行的时候再赋具体的值
  • Tensorflow的计算流图有助于优化整个系统的代码,首先构筑整个系统的graph(静态的),代码并不会直接生效,在实际的运行时,启动一个session,程序才会真正的运行。
  • placeholder用feed_dict来实际传值,它用一个字典结构来赋值。
  • 其实feed_dict可以喂数据给其他tensor,不止placeholder这一种。

 总结:当要创建一个变量时,首先placeholder把变量的类型,大小/shape指定好, 实际上并不往里面传值,可用于batch更新,具体等于什么值要在session中计算,实际传值要用feed_dict。

input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.matmul(input1, input2)
with tf.Session() as sess:
    print(sess.run([output], feed_dict={input1:[7.], input2:[2.]}))

5. tf.placeholder 与 tf.Variable的区别

  • Variable在声明时必须赋予初始值,在训练过程中该值很可能会进行不断的加减操作变化;主要是用于训练变量之类的。比如网络权重和偏置。
  • placeholder也用于存储数据,在命名时不需要赋值,但主要用feed_dict来接收输入数据。placeholder值在训练过程中会不断地被赋予新的值,用于批训练,基本上其值是不会轻易进行加减操作

6.其它关于tensorflow图像处理的建议:

  •  tensorflow默认使用mnist的next_batch()的batch_size,不使用该数据集时,要先导入自己的数据,再转换并堆叠成batch_size。
  •  找关于图像处理的开源项目去GitHub上搜【FasterRCNN】或者【nmt】
  • Windows建议用Ubuntu系统,不建议用虚拟机。
  • 网页搜索框里输入【关键字+benchmark】,可以搜到一些网站,里面有论文,代码,算法,实验结果。
  • MPII是人体关键点的database
  • 关于人脸的一个论坛 ThinkFace
  • YOLO2:实时目标检测
  • Stack Overflow 上搜资源:迁移学习,注意力机制

参考

【1】tf.placeholder使用说明 - CSDN博客

【2】tf.placeholder 与 tf.Variable区别对比- CSDN博客

【3】Tensorflow 解惑[二]:feed_dict不一定与placeholder捆绑

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值