1、Session实例
import tensorflow as tf# 搭建计算图
node1 = tf.constant(2.0, tf.float32, name='node1')
node2 = tf.constant(3.0, tf.float32, name='node2')
node3 = tf.add(node1, node2)'''使用Session的模式一'''
sess = tf.Session() # 创建会话
print('node3运算结果为:', sess.run(node3)) # 运行计算图
sess.close() # 关闭会话'''使用Session的模式二'''
# with tf.Session() as sess:
# print(sess.run(node3)) # 运行计算图'''指定默认的Session第一种方式'''
# sess = tf.Session()
# with sess.as_default():
# print(node3.eval())'''指定默认的Session第二种方式'''
# sess = tf.Session()
# print(node3.eval(session=sess))
# sess.close()'''交互式环境下构建默认会话'''
# sess = tf.InteractiveSession()
# print(node3.eval())
# sess.close()
2、常量
import tensorflow as tf# 定义常量
tensor = tf.constant(5, tf.int8, shape=[2, 3], name='tensor')
tensor1 = tf.constant([1, 2, 3], tf.int8, name='tensor1')zeros = tf.zeros([2, 3], tf.int8, name='zeros')
ones = tf.ones([2, 3], tf.int8, name='ones')
fill = tf.fill([2, 3], 6, name='fill')name_list = [tensor.name, tensor1.name, zeros.name, ones.name, fill.name]# 运行图
cont = 0
with tf.Session() as sess:for i in sess.run([tensor, tensor1, ones, zeros, fill]):print(name_list[cont], ' shape:', i.shape)print(i, '\n')cont += 1
3、变量
import tensorflow as tfvariable = tf.Variable(12, tf.int8, name='variable')# variable1 = tf.get_variable()# 单个变量初始化
# init_op = variable.initializer()# 所以变量初始化
init_op = tf.global_variables_initializer()with tf.Session() as sess:sess.run(init_op)print(sess.run(variable))
4、Fetch and Feed
import tensorflow as tf# Fetch 会话中可以去执行多个op,得到他运行的结果
input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)add = tf.add(input2, input3)
mul = tf.multiply(input1, add)with tf.Session() as sess:# 会话中同时运行两个op,fetch的意思:会话中同时运行多个opresult = sess.run([mul, add])print(result)# Feed
# 创建占位符,在会话中使用
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1, input2)
with tf.Session() as sess:# feed的数据以字典的形式传入print(sess.run(output, feed_dict={input1: [7.], input2: [2.]}))