Tensorflow 中 python3.6 中 with...as... : 用法的理解

版权声明:本文为博主原创文章,转载标注出处。 https://blog.csdn.net/qq_36666115/article/details/80017050

[转载请联系版主]

首先看一段代码

x = tf.placeholder(tf.float32, shape=(1, 2))
w1 = tf.Variable(tf.random_normal([2, 3],stddev=1,seed=1))
w2 = tf.Variable(tf.random_normal([3, 1],stddev=1,seed=1))

a = tf.matmul(x,w1)
y = tf.matmul(a,w2)

with tf.Session() as sess:
    # 变量运行前必须做初始化操作
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    print(sess.run(y, feed_dict={x:[[0.7, 0.5]]}))

这段代码说的是一个简单的神经网络。别的都可以看懂,但有一个结构特别

with tf.Session() as sess:
    sess.run()

首先查一查文档的说明


# Using the `close()` method.  方法一
sess = tf.Session()
sess.run(...)
sess.close()

# Using the context manager.  方法二
with tf.Session() as sess:
  sess.run(...)

其实这里有两种方法,第一种类似于打开文件,最后需要关闭一下;
而第二个方法,则无需要,很简单。所以我们来认知一下它

今天主题:看定义

class controlled_execution:

    def __enter__(self):

        set things up

        return thing

    def __exit__(self, type, value, traceback):

        tear things down
with controlled_execution() as thing:

        do something

当python执行这一句时,会调用enter函数,然后把该函数return的值传给as后指定的变量。之后,python会执行下面do something的语句块。最后不论在该语句块出现了什么异常,都会在离开时执行exit
另外,exit除了用于tear things down,还可以进行异常的监控和处理,注意后几个参数。要跳过一个异常,只需要返回该函数True即可。下面的样例代码跳过了所有的TypeError,而让其他异常正常抛出。

参考文献:
理解with
Tensorflow文档
tensorflow中python中with用法的理解

猜你喜欢

转载自blog.csdn.net/qq_36666115/article/details/80017050