tensor可简单的理解为多维数组,但是张量对象并未正真保存计算的结果值, 而是保存要获得这个值的计算过程。
import tensorflow as tfa = tf.constant([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]], dtype=tf.float32)b = tf.constant([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]], dtype=tf.float32)result = a+bprint(result)with tf.Session() as session: b = session.run(result) print(b)
tensorflow Graph:
import tensorflow as tf# 新建一个计算图g1 = tf.Graph()with g1.as_default(): v = tf.get_variable("v", [1], initializer=tf.zeros_initializer()) # 设置初始值为0# 新建另一个计算图g2 = tf.Graph()with g2.as_default(): v1 = tf.get_variable("v1", [1], initializer=tf.ones_initializer()) # 设置初始值为1 result = v1 + 1# 新建一个session对话with tf.Session(graph=g1) as sess: tf.global_variables_initializer().run() with tf.variable_scope("", reuse=True): print(sess.run(tf.get_variable("v")))# 新建另一个session对话with tf.Session(graph=g2) as sess: tf.global_variables_initializer().run() with tf.variable_scope("", reuse=True): print(sess.run(tf.get_variable("v1"))) print(sess.run(result))
常量:常量也要看作是一个张量
import tensorflow as tfa = tf.constant([1.0, 2.0], name="a")b = tf.constant([2.0, 3.0], name="b")result = a + bprint(result)with tf.Session() as sess:#即便是一个常量,也需要session通过运算得到。 print(sess.run(result)) print(result.eval()) sess.close()
会话:
# 创建一个会话。sess = tf.Session()#
sess = tf.InteractiveSession () 可为交互式会话。
# 使用会话得到之前计算的结果。print(sess.run(result))# 关闭会话使得本次运行中使用到的资源可以被释放。sess.close()
config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True)#配置会话sess1 = tf.InteractiveSession(config=config)sess2 = tf.Session(config=config)
一个简单的前向传播
import tensorflow as tf# 初始化随机值init_w1 = tf.random_normal([2, 3], stddev=1, seed=1)w1 = tf.Variable(init_w1)init_w2 = tf.random_normal([3, 1], stddev=1, seed=1)w2 = tf.Variable(init_w2)x = tf.constant([[0.7, 0.9]])a = tf.matmul(x, w1)y = tf.matmul(a, w2)sess = tf.Session()sess.run(w1.initializer)sess.run(w2.initializer)print(sess.run(y))sess.close()# 新的输入类型x = tf.placeholder(tf.float32, shape=(1, 2), name="input")a = tf.matmul(x, w1)y = tf.matmul(a, w2)sess = tf.Session()init_op = tf.global_variables_initializer()sess.run(init_op)print(sess.run(y, feed_dict={x: [[0.7, 0.9]]}))# 批量inputx = tf.placeholder(tf.float32, shape=(3, 2), name="input")a = tf.matmul(x, w1)y = tf.matmul(a, w2)sess = tf.Session()# 使用tf.global_variables_initializer()来初始化所有的变量init_op = tf.global_variables_initializer()sess.run(init_op)print(sess.run(y, feed_dict={x: [[0.7, 0.9], [0.1, 0.4], [0.5, 0.8]]}))