TensorFlow 笔记
Deep Learning
import tensorflow as tf
x = 1
y = 2
add_op = tf.add(x, y, name='add_op')
mul_op = tf.multiply(x, y, name='mul_op')
pow_op = tf.pow(add_op, mul_op, name='pow_op')
"""
x--(+)-------\
X (**)
y--(*)-------/
"""
print(pow_op)
"""
>>> Tensor("pow_op:0", shape=(), dtype=int32)
"""
with tf.Session() as sess:
print(sess.run(pow_op))
"""
>>> 9
"""
useless = tf.multiply(x, add_op, name='useless')
with tf.Session() as sess:
sess.run(pow_op)
pow_op_result, useless_result = sess.run([pow_op, useless])
"""
>>> [9, 3]
"""
"""
tf.Session.run(fetches,
feed_dict=None,
options=None,
run_metadata=None)
fetches 为想要计算的结点(Tensor)列表
"""
with tf.device('/gpu:1'):
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name='b')
c = tf.multiply(a, b, name='c')
with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:
print(sess.run(c))
"""
>>> c: (Mul): /job:localhost/replica:0/task:0/device:GPU:1
>>> b: (Const): /job:localhost/replica:0/task:0/device:GPU:1
>>> a: (Const): /job:localhost/replica:0/task:0/device:GPU:1
(这里从日志输出顺序也可看出惰性求值的求值顺序)
"""
g = tf.Graph()
with g.as_default():
x = tf.add(3, 5, name='x in g')
with tf.Session(graph=g) as sess:
sess.run(x)
g_default = tf.get_default_graph()
with g_default.as_default():
m = tf.constant(1)
with g.as_default():
n = tf.constant(2)