前面做完了tensorflow的安装https://blog.csdn.net/zhouzhouasishuijiao/article/details/84986474
后面尝试自己做tensorflow的一些事情,对零散的知识点进行一些总结,主要留给自己备用
- tensorflow中两种作用域
name scope(命名域):通过tf.name_scope()来实现
variable scope(变量域):通过tf.variable_scope()来实现;可以通过reuse标志以及初始化方式来影响域下的变量
两种方式都回给变量加上词头
import tensorflow as tf
with tf.name_scope('cltdevelop'):
var_1 = tf.Variable(initial_value=[0], name='var_1')
var_2 = tf.get_variable(name='var_2', shape=[1, ])
with tf.variable_scope('aaa'):
var_3 = tf.Variable(initial_value=[0], name='var_3')
var_4 = tf.get_variable(name='var_4', shape=[1, ])
print(var_1.name)
print(var_2.name)
print(var_3.name)
print(var_4.name)
在tensorflow中变量共享机制是通过tf.get_variable()和tf.variable_scope()两者搭配使用来实现的。
import tensorflow as tf
with tf.variable_scope('cltdevelop'):
var_1 = tf.get_variable('var_1', shape=[1, ])
with tf.variable_scope('cltdevelop', reuse=True):
var_2 = tf.get_variable('var_1', shape=[1,])
print(var_1.name)
print(var_2.name)
当reuse设置为True或者tf.AUTO_REUSE时,表示这个scope下的变量是宠用的或者共享的,也说明这个变量以签就已经创建好了。但是如果这个变量之前没有创建过,则在tf.variable_scope下调用tf.get_variable创建这个变量会报错。
- 张量 tf.tensor
经过短暂的使用,发现tensorflow有个特殊的变量,叫做张量,这个变量既能作为变量在运算过程中作为操作数,也能作为一行代码的标记,最终,在会话中被使用
- 会话 session
tensorflow的运算模式是先定义过程,然后在调用该过程进行运算,session()就是用于调用运算过程。
import numpy as np
import tensorflow as tf
a=np.linspace(0,4,5)
b=np.linsapce(4,8,5)
c=np.add(a,b)#这里c就成为了张量
d=np.add(b,c)#这里可以把c运用到运算里面
# session的第一种定义方式
sess=tf.session()
sess.run(c)
# session的第二种定义方式
with tf.Session() as sess:
sess.run(d)