Fork me on GitHub

Session的用法

Session的用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#author:victor

#Session的用法讲解
#import module
import tensorflow as tf

#define two constant matrix
matrix1=tf.constant([[3,3]])
matrix2=tf.constant([[2],
[2]])
#using matrix multiply
product=tf.matmul(matrix1,matrix2)#matrix multiply 在numpy中是np.dot(matrix1,matrix2)

#method 1
#从session中的run中获取结果
sess=tf.Session()
result=sess.run(product)
print(result)
sess.close()

#method 2
#session自动close,推荐适用这个
with tf.Session() as sess:
result2=sess.run(product)
print(result2)

运行结果

Session

总结:

  • sess=tf.InteractiveSession()
  • with sess.as_default():
  • with tf.Session() as sess:
  • sess=tf.Session()