Tensorflow中Session会话控制

Session是Tensorflow为了控制和输出文件的执行语句。运行Session.run()可以获得你想要的运算结果。

举个例子:

用Tensorflow实现两个矩阵相乘,并输出结果。

首先,我们先加载Tensorflow,然后建立两个matrix,输出两个matrix相乘的结果。因为product是直接计算的步骤,所有我们要使用Session来激活product,并得到计算结果。

import tensorflow as tf

matrix1 = tf.constant([[3,3]])
matrix2 = tf.constant([[2],[2]])

product = tf.matmul(matrix1,matrix2)  # matrix multiply np.dot(m1,m2)

# method 1
sess = tf.Session()
result = sess.run(product)
print(result)
sess.close()

方法二:

因为Session是一个对象,使用完后需要close。在编程的时候,我们往往容易忘记close(),所以我们可以使用With更加简洁的语句来实现。

先说一下Python中with的作用:

(1)使用with后不管with中的代码出现什么错误,都会进行对当前对象进行清理工作。例如file的file.close()方法,无论with中出现任何错误,都会执行file.close()方法

(2)with只有在特定场合下才能使用。这个特定场合指的是那些支持了上下文管理器的对象。

这些对象包括:

file
decimal.Context
thread.LockType
threading.Lock
threading.RLock
threading.Condition
threading.Semaphore
threading.BoundedSemaphore

这些对象都是Python里面的,当然在Tensorflow中还有Session对象啦!

那么什么是上下文管理器呢??

这个管理器就是在对象内实现了两个方法:__enter__() 和__exit__()

  __enter__()方法会在with的代码块执行之前执行,__exit__()会在代码块执行结束后执行。

  __exit__()方法内会自带当前对象的清理方法。

with语句类似

  try :

  except:

  finally:

的功能。但是with语句更简洁。而且更安全。代码量更少。

import tensorflow as tf

matrix1 = tf.constant([[3,3]])
matrix2 = tf.constant([[2],[2]])

product = tf.matmul(matrix1,matrix2)  # matrix multiply np.dot(m1,m2)

# method 2
with tf.Session() as sess:
    result2 = sess.run(product)
    print(result2)

观看视频笔记:https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/2-3-session/

Reference:

(参考关于Python中With用法)https://www.cnblogs.com/zhangkaikai/p/6669750.html

猜你喜欢

转载自blog.csdn.net/program_developer/article/details/80170584