tensoflow学习入门一

对于如何创建图并开启session,参考如下

# -- encoding:utf-8 --


import tensorflow as tf

# 定义常量矩阵a和矩阵b

a=tf.constant([[1,2],[3,4]],dtype=tf.int32)

b=tf.constant([5,6,7,8],dtype=tf.int32,shape=[2,2])

# 2.以a和b做为输入,进行矩阵的乘法操作.

c=tf.matmul(a,b,name='matmu1')

print(type(c))
print(c)

# 3.以a和c为输入,进行矩阵的加法操作

g=tf.add(a,c,name='add')
print(g)

# 4.添加减法
h=tf.subtract(b,a,name='b-a')
l=tf.matmul(h,c)
r=tf.add(g,l)

# 回话构建和启动
sess=tf.Session()
print(sess)

# 调用session的run方法来执行矩阵的加法,得到c的记过值
# 不需要考虑图中间的运算,在允许的时候只需要关注最终结果对应的对象已经所需要的输入数据值
# 只需要传递仅需所需要得到的结果对象,会自动的根据图中的依赖关系触发所有相关的OP操作的执行
# 如果op之间没有依赖关系,tensorflow底层会并行的执行op -->自动进行
# fetches:表示获取那个op操作的结果值
result=sess.run(fetches=[c,r])
print("type:{},value:{}".format(type(result),result))
# print(r.eval())

# 关闭回话
sess.close()

# 使用with 方法创建session 可以自动关闭session.
with tf.Session() as sess2:
    print(sess2)
    print("sess2 run:{}",format(sess2.run(c)))
    print("c eval:{}".format(c.eval()))

#交互式回话构建
sess3=tf.InteractiveSession()
print("InteractiveSession>>>>>>>>")
print(r.eval())
print(sess3.run(c))



# print("变量a是否在默认图中:{}".format(a.graph is tf.get_default_graph()))
#
# # 使用新的构建的图
# graph=tf.Graph()
# with graph.as_default():
#     # 此时在这个代码块中,使用的就是新的定义的图graph(相当于把默认图换成了graph)
#     d=tf.constant(5.0)
#     print("变量d是否在新图graph中:{}".format(d.graph is graph))
#     print(d.graph is tf.get_default_graph())
# with tf.Graph().as_default() as g2:
#     e=tf.constant(6.0)
#     print("变量e是否在新图g2中:{}".format(e.graph is g2))

# 错误的操作
# f=tf.add(d,e)
# print("变量f的图;{}".format(f.graph))
原文地址:https://www.cnblogs.com/yuluoxingkong/p/9073914.html