TensorFlow学习01
tf.Session()
tf.Session()是运行tensorflow operation的类。tensorflow中最基本的类型是tensor(张量),所以Session 丰庄路所有op运行的环境。
Session可能拥有资源,所以不用session的时候需要释放它,一般有两种用法,通常用第二种:
- sess=tf.Session()
sess.run(…)
sess.close() - With tf.Session() as sess:
sess.run(…)
Session中的类的初始化
init(
target=’’,
graph=None,
config=None
)
初始化时候需要传入一个graph,如果没有指定graph,那么会使用默认的graph,即等价graph=tf.get_default_graph()
sess.run()
run(
fetches,
feed_dict=None,
options=None,
run_metadata=None
)
run运行op并且返回在fetches中的tensor。sess.run(A)只运行为了完成run中操作的必要的graph中的操作,并且对在fetches中每一个tensor的值
fetches的值可能是一个graph中的元素,或者一个list,tuple,dict等
如果fectches的值是一个tf.Operation那么返回值为None;如果是tf.Tensor那么相应的fetched value即为numpy.ndarray(值为张量计算后的value)
例子
a = tf.constant([10, 20])
b = tf.constant([1.0, 2.0])
# 'fetches' can be a singleton
v = session.run(a)
# v is the numpy array [10, 20]
# 'fetches' can be a list.
v = session.run([a, b])
# v is a Python list with 2 numpy arrays: the 1-D array [10, 20] and the
# 1-D array [1.0, 2.0]
# 'fetches' can be arbitrary lists, tuples, namedtuple, dicts:
MyData = collections.namedtuple('MyData', ['a', 'b'])
v = session.run({'k1': MyData(a, b), 'k2': [b, a]})
# v is a dict with
# v['k1'] is a MyData namedtuple with 'a' (the numpy array [10, 20]) and
# 'b' (the numpy array [1.0, 2.0])
# v['k2'] is a list with the numpy array [1.0, 2.0] and the numpy array
# [10, 20].