import tensorflow as tf
#创建一个常量
c = tf.constant( [[2,3],[4,5]],name="const1",dtype=int64 )
#输出c:<tf.Tensor 'const1:0' shape=(2,2) dtype=int64>
#创建会话,需要关闭
sess = tf.Session()
sess.run(c)
'''
array([[2,3],
[4,5]])
'''
print( sess.run(c) )
'''
([[2,3],
[4,5]])
'''
#值得注意的是,Graph是非线程安全的
if c.graph is tf.get_default_graph():
print("tensor 会创建一个默认的Graph")
sess.close()
最简单的介绍,下面是一个比较完整的例子
import tensorflow as tf
const1 = tf.constant([2,2])
const2 = tf.constant([[4],
[4]])
multiple = tf.matmul(const1,const2)
print(multiple)
#只会显示multiple的信息,不会显示其值
sess = tf.Session()
#用run来实际运行 multiple这个矩阵乘法操作
result = sess.run(multiple)
print(result)
if const1.graph is tf.get_default_graph() :
print("const1 所在图是当前默认图")
sess.close()
#第二种方法使用Session
# sess 会自动关闭,不需要手动close
#不过要内容会受到 with 范围的限制
with tf.Session() as sess:
result2 = sess.run(multiple)
print("Multiple的结果是 %s" % result2)