会话
会话拥有并管理TensorFlow程序运行时的所有资源
当所有计算完成之后要关闭会话,帮助系统回收资源
import tensorflow as tf
# 定义计算图
tens1 = tf.constant([1,2,3])
# 创建一个会话
sess = tf.Session()
# 使用会话来得到运算结果
result= sess.run(tens1)
print(result)
# 关闭会话并释放资源
sess.close()
[1 2 3]
会话模式一
# 定义计算图
tens2= tf.constant([1,2,3])
# 创建一个会话
sess = tf.Session()
# 使用会话来得到运算结果
try:
print(sess.run(tens2))
except:
print("Exception!")
finally:
# 关闭会话并释放资源
sess.close()
[1 2 3]
会话模式二
node1 = tf.constant(3.0, tf.float32, name="node1")
node2 = tf.constant(4.0, tf.float32, name='nmde2')
result=tf.add(node1,node2)
# 创建一个会话,并用Python的上下文管理器来管理这个会话
with tf.Session() as sess:
print(sess.run(result))
# 改方法不需要再使用sess.close()方法。
7.0
指定默认会话,需要手动指定
TensorFlow不会自动生成默认会话,需要手动指定当默认的会话被指定后可以通过tf.Tensor.eval函数来计算一个张量的取值
node1 = tf.constant(3.0, tf.float32, name='node1')
node2 = tf.constant(4.0, tf.float32, name='node2')
result = tf.add(node1, node2)
sess = tf.Session()
with sess.as_default():
print(result.eval())
# 可以发现print(sess.run(result)) 与print(result.eval(session=sess)) 相同
7.0
交互式环境下设置默认会话
在交互式环境下,Python脚本或者Jupyter编辑器下,通过设置默认会话来获取张量的取值
更加方便
tf.InteractiveSession 使用这个函数会自动将生成的会话注册为默认会话
常量与变量
常量constant
在运行过程中值不会改变的单元,在TensorFlow中无须进行初始化操作
创建语句:
constant_ name = tf.constant(value)
a = tf.constant(1.0, name='a')
b = tf.constant(2.5, name='b')
c = tf.add(a, b, name='c')
sess = tf.Session()
c_value = sess.run(c)
print(c_value)
sess.close()
3.5
变量 Variable
在运行过程中值会改变的单元,在TensorFlow中须进行初始化操作
创建语句:
name_variable = tf.Variable(value, name)
个别变量初始化:
init_op = name_variable.initializer()
所有变量初始化:
init_op = tf.global_variables_initializer()
a = tf.Variable(1.0, name='a')
b = tf.Variable(2.5, name='b')
c = tf.add(a, b, name='add')
sess = tf.Session()
init = tf.global_variables_initializer() # 增加了一个init初始化的变量
sess.run(init)
c_value = sess.run(result)
print(c_value)
sess.close()
7.0
变量赋值
- 与传统编程语言不同,TensorFlow中的变量定义后,一般无需人工赋值,
系统会根据算法模型,训练优化过程中自动调整变量对应的数值 - 后面在将机器学习模型训练时会更能体会,比如权重Weight变量w,经
过多次迭代,会自动调
epoch = tf.Variable(0,name='epoch',trainable=False)
- 特殊情况需要人工更新的,可用变量赋值语句
变量更新语句:
update_op = tf.assign(variable_to_be_updated, new_value)
# 变量赋值
value = tf.Variable(0, name= 'value')
one = tf.constant(1)
new_value = tf.add(value, one)
update_value = tf.assign(value, new_value) # 更新变量
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for _ in range(10):
sess.run(update_value)
print(sess.run(value))
1
2
3
4
5
6
7
8
9
10
思考题
如何通过TensorFlow的变量赋值计算:1+2+3+…+10 ?
value =tf.Variable(1, name="value")
sums = tf.Variable(0)
one = tf.constant(1)
new_sums = tf.add(sums,value)
update_sums = tf.assign(sums, new_sums)
new_value = tf.add(value, one)
update_value = tf.assign(value,new_value)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for _ in range(10):
sess.run(update_sums)
sess.run(update_value)
print(sess.run(sums))
55
占位符
占位符 placeholder
-
TensorFlow中的Variable变量类型,在定义时需要初始化,但有些变量
定义时并不知道其数值,只有当真正开始运行程序时,才由外部输入,
比如训练数据,这时候需要用到占位符 -
tf.placeholder占位符,是TensorFlow中特有的一种数据结构,类似动
态变量,函数的参数、或者C语言或者Python语言中格式化输出时的“%”
占位符 -
TensorFlow占位符Placeholder,先定义一种数据,其参数为数据的
Type和Shape
占位符Placeholder的函数接口如下:
tf.placeholder(dtype, shape=None, name=None)
x = tf.placeholder(tf.float32, [2,3], name= 'tx')
# 生成一个2*3的二维2数组
Feed提交数据和Fetch提取数据
Feed提交数据
如果构建了一个包含placeholder操作的计算图,当在session中调用run方
法时,placeholder占用的变量必须通过feed_dict参数传递进去,否则报错
a = tf.placeholder(tf.float32,name='a')
b = tf.placeholder(tf.float32,name='b')
c = tf.multiply(a, b, name='c')
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
result = sess.run(c, feed_dict={a: 8.0, b: 3.5})
print(result)
28.0
多个操作可以通过一次Feed完成执行
a = tf.placeholder(tf.float32, name='a')
b = tf.placeholder(tf.float32, name='b')
c = tf.multiply(a,b,name='c')
d = tf.subtract(a,b,name='d')
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
result = sess.run([c,d], feed_dict={a:[8.1,2.0,3.5], b:[1.5,2.0,4.0]})
print(result)
print(result[0])
[array([ 12.15000057, 4. , 14. ], dtype=float32), array([ 6.60000038, 0. , -0.5 ], dtype=float32)]
[ 12.15000057 4. 14. ]
一次返回多个值分别赋给多个变量
a = tf.placeholder(tf.float32, name='a')
b = tf.placeholder(tf.float32, name='b')
c = tf.multiply(a,b,name='c')
d = tf.subtract(a,b,name='d')
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
rc, rd = sess.run([c,d], feed_dict={a:[8.1,2.0,3.5], b:[1.5,2.0,4.0]})
print(rc)
print(rd)
[ 12.15000057 4. 14. ]
[ 6.60000038 0. -0.5 ]