Python TensorFlow,会话,Session,会话的run()方法,placeholder占位符,feed操作

TensorFlow分为前端系统(定义程序的图结构)和后端系统(运行图结构)。

会话的作用:1、运行图的结构    2、分配资源计算(分配CPU、GPU)    3、管理资源(变量、队列、线程等。会话结束后需要释放)

demo.py(会话,Session):

import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'  # 设置警告级别


# 手动创建计算图。
new_graph = tf.Graph()

# 在新创建的计算图中添加张量
with new_graph.as_default():
    b = tf.constant(666.0)

a = tf.constant(5.0)  # 张量a自动属于默认的计算图。


# 会话(运行计算图的类,使用默认注册的图(也可以手动指定计算图),一个会话只能运行一个计算图)
with tf.Session() as sess:
    print(sess.run(a))  # 5.0

# 会话(手动指定计算图)
with tf.Session(graph=new_graph) as sess:
    print(sess.run(b))  # 666.0

# 会话 config参数。 log_device_placement表示运算所用设备的日志信息
with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:
    print(sess.run(a))
    '''
    Device mapping: no known devices.
    Const: (Const): /job:localhost/replica:0/task:0/cpu:0   Const运算使用的是cpu
    5.0
    '''
    

交互式会话:InteractiveSession (一般在ipython中使用):

In [1]:  import tensorflow as tf
In [2]:  a = tf.constant(3.0)
In [3]:  tf.InteractiveSession()
Out[3]:  <tensorflow.python.client.session.InteractiveSession at 0x7f99003e43c8>
In [4]:  a.eval()
Out[4]:  3.0


demo.py(会话的run()方法,placeholder占位符,feed操作):

import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'  # 设置警告级别


a = tf.constant(5.0)
b = tf.constant(6.0)
sum1 = tf.add(a, b)

var1 = 1.0  # 普通变量

# placeholder表示占位符(不确定输入什么),一般配合feed_dict使用(训练的时候实时地提供数据,run()执行时才会提供数据)
plt = tf.placeholder(dtype=tf.float32, shape=[None, 3])  # shape中的None表示行数可以任意,3表示列数。

# 会话
with tf.Session() as sess:
    print(sess.run([a, b, sum1]))  # [5.0, 6.0, 11.0]  run()方法可以运行张量或运算操作。
    # print(sess.run(var1))  # 会报错。 run()方法不能运行普通变量。
    print(sess.run(a + var1))  # 张量与普通变量相加,结果也是一个张量。(TensorFlow重载了+-*/等运算符)

    # run()实时地提供数据。 将feed_dict中的实时数据替换占位符。(替换的数据要与占位符的shape对应)
    print(sess.run(plt, feed_dict={plt:[[1,2,3], [4,5,6]]}))
    '''
    [[1. 2. 3.]
     [4. 5. 6.]]
    '''


'''
run()方法的常见异常错误:
RuntimeError:如果它Session处于无效状态(例如已关闭)。
TypeError:如果fetches或feed_dict键是不合适的类型。
ValueError:如果fetches或feed_dict键无效或引用 Tensor不存在。
'''

猜你喜欢

转载自blog.csdn.net/houyanhua1/article/details/88087948