tensorflow 笔记
Just some personal notes for tensorflow, I will sort it out once I get a time.
计算图
- tensorflow 通过 variable 来构建计算图
- tensor.graph 获取当前在哪个图
- tf.get_default_graph() 获取当前默认图
- tf.Graph() 创建图
- with graph1.as_default(): 图内定义计算
- tf.Session(graph=g1),需要图来进行初始化,默认是当前默认图
- with graph1.device(‘/gpu:0’): 定义操作在哪个处理器上跑,也可以tf.device(‘/gpu:0’)对默认图进行使用
- 通过 collection 来管理资源
- add_to_collection(name, value) ,get_collection(name, scope=None)
- Variable用于存储网络中的权重矩阵等变量,而Tensor更多的是中间结果等。(也就是说variable 是子节点,tensor 是中间节点
- Tensor可以使用的地方,几乎都可以使用Variable。
- tensor 会记录产生其的操作与数据,也会记录其参加的操作
- variable 做任何运算的结果都是tensor,variable 需要自己指定,不然在图中都是tensor
- pytorch 由于是动态图,图上都是variable,但是只有leaf variable 才是tensorflow 意义上的variable(两者的 variable 是不同的,tensorflow 只有名字,类型,pytorch有了shape, )
- define and run, define by run.
- tensor-like 数据都可以用 tensorflow的运算,如variable, tensor, ndarray, list, bool, float, int ,str
- summery.FileWrite(‘loc’, sess.graph)
- saver
变量共享
- get_variable 来生成变量
- 在同一个 variable_scope 里进行操作
- 操作前后调用 scope.reuse_variables()
- tf.Variable(), tf.get_variable(), tf.Variable_scope(), tf.name_scope()
- tf.Variable() 自行处理冲骨头
- tf.get_variable(),重名且非共享变量,出错
- variable_scope 允许共享变量
- v = tf.get_variable(name, shape, dtype, initializer)
with tf.variable_scope('variable_scope_y') as scope:
var1 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32)
scope.reuse_variables() # 设置共享变量
var1_reuse = tf.get_variable(name='var1')
var2 = tf.Variable(initial_value=[2.], name='var2', dtype=tf.float32)
var2_reuse = tf.Variable(initial_value=[2.], name='var2', dtype=tf.float32)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(var1.name, sess.run(var1))
print(var1_reuse.name, sess.run(var1_reuse))
print(var2.name, sess.run(var2))
print(var2_reuse.name, sess.run(var2_reuse))
# 输出结果:
# variable_scope_y/var1:0 [-1.59682846]
# variable_scope_y/var1:0 [-1.59682846] 可以看到变量var1_reuse重复使用了var1
# variable_scope_y/var2:0 [ 2.]
# variable_scope_y/var2_1:0 [ 2.]
with tf.variable_scope("image_filters1") as scope1:
result1 = my_image_filter(image1)
with tf.variable_scope(scope1, reuse = True)
result2 = my_image_filter(image2)
embedding
word_embeddings = tf.get_variable(“word_embeddings”,
[vocabulary_size, embedding_size])
embedded_word_ids = tf.gather(word_embeddings, word_ids)
#or
embed = tf.nn.embedding_lookup(word_embeddings, word_ids)
参考
- https://www.cnblogs.com/duanv/p/5947525.html
- http://www.cnblogs.com/Charles-Wan/p/6200446.html
- http://wiki.jikexueyuan.com/project/tensorflow-zh/how_tos/variable_scope.html
- https://www.tensorflow.org/programmers_guide/variables
- http://www.cs.cornell.edu/courses/cs5740/2017sp/lectures/04-nn-compgraph.pdf
- https://www.packtpub.com/mapt/book/big_data_and_business_intelligence/9781786469786/2/ch02lvl1sec21/computational-graphs
- http://www.cs.cornell.edu/courses/cs5740/2017sp/
- https://www.tensorflow.org/versions/r1.3/programmers_guide/graphs
- https://www.tensorflow.org/tutorials/word2vec