# 开启交互式Session sess = tf.InteractiveSession() a = tf.constant(5.0) b = tf.constant(6.0) c = a * b x = tf.Variable([1.0, 2.0]) # 无需显式在`sess.run`中执行 # 直接调用`OPs.eval/run()`方法得到结果 x.initializer.run() print(c.eval()) sess.close()
import tensorflow as tf import tensorflow.contrib.eager as tfe # 启用TF eager execution tfe.enable_eager_execution()
优势
支持python debug工具
提供实时报错
支持python数据结构
支持pythonic的控制流
1 2 3
i = tf.constant(0) whlile i < 1000: i = tf.add(i, 1)
eager execution开启后
tensors行为类似np.ndarray
大部分API和未开启同样工作,倾向于使用
tfe.Variable
tf.contrib.summary
tfe.Iterator
tfe.py_func
面向对象的layers
需要自行管理变量存储
eager execution和graph大部分兼容
checkpoint兼容
代码可以同时用于python过程、构建图
可使用@tfe.function将计算编译为图
示例
placeholder、sessions
1 2 3 4 5 6 7 8 9
# 普通TF x = tf.placholder(tf.float32, shape=[1, 1]) m = tf.matmul(x, x) with tf.Session() as sess: m_out = sess.run(m, feed_dict={x: [[2.]]})
# Eager Execution x = [[2.]] m = tf.matmul(x, x)
Lazy loading
1 2 3 4 5
x = tf.random_uniform([2, 2]) for i inrange(x.shape[0]): for j inrange(x.shape[1]): # 不会添加多个节点 print(x[i, j])
Device
设备标识
设备标识:设备使用字符串进行标识
/cpu:0:所有CPU都以此作为名称
/gpu:0:第一个GPU,如果有
/gpu:1:第二个GPU
1 2 3 4 5 6
# 为计算指定硬件资源 with tf.device("/gpu:2"): a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0], name="a") b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0], name="b") c = tf.multiply(a, b) # creates a graph
identifier ::= xid_start xid_continue* id_start ::= <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property> id_continue ::= <all characters in id_start, plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property> xid_start ::= <all characters in id_start whose NFKC normalization is in "id_start xid_continue*"> xid_continue ::= <all characters in id_continue whose NFKC normalization is in "id_continue*">
Lu:大写字母
Ll:小写字母
Lt:词首大写字母
Lm:修饰字母
Lo:其他字母
Nl:字母数字
Mn:非空白标识
Mc:含空白标识
Nd:十进制数字
Pc:连接标点
Other_ID_Start:由PropList.txt定义的显式字符列表,
用来支持向后兼容
Other_ID_Continue:同上
Keywords
关键字:以下标识符作为语言的保留字、关键字,不能用作普通
标识符
1 2 3 4 5 6 7
False await else import pass None break except in raise True class finally is return and continue for lambda try as def from nonlocal while assert del global not with async elif if or yield
defecho(value=None): print("execution start") try: whileTrue: try: value = (yield value) except Exception as e: value = e finally: print("clean up when gen.close() is called")