我可以在没有“with”语句的情况下调用tf.variable_scope吗?

时间:2018-05-02 06:26:00

标签: python matlab tensorflow

我想在matlab中调用tensorflow的python API(参见https://www.mathworks.com/help/matlab/matlab_external/call-python-from-matlab.html)。 matlab不支持“with”语句。 我不能创建没有“with”语句的tf.variable_scope。 我试过下面的两个代码,但两个都不起作用。 有没有解决方案?

的Python:

org.openqa.selenium.WebDriverException: unknown error: Chrome failed to start: crashed
  (Driver info: chromedriver=2.37.544315 (730aa6a5fdba159ac9f4c1e8cbc59bf1b5ce12b7),platform=Linux 4.4.111-boot2docker x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 60.18 seconds
Build info: version: '3.11.0', revision: 'e59cfb3', time: '2018-03-11T20:26:55.152Z'
System info: host: '0b467c07b27d', ip: '***.****.****.**', os.name: 'Linux', os.arch: 'amd64', os.version: '4.4.111-boot2docker', java.version: '1.8.0_171'
Driver info: driver.version: ChromeDriver

Matlab的:

import tensorflow as tf
with tf.variable_scope('123') as vs:
    print(vs.name)  # OK
vs2 = tf.variable_scope('456')
print(vs2.name)  # AttributeError: 'variable_scope' object has no attribute 'name'

2 个答案:

答案 0 :(得分:1)

您可以重写像

这样的python上下文
import tensorflow as tf

with tf.variable_scope('123') as vs:
    print(vs.name)  # OK


vs2_obj = tf.variable_scope('456')
vs2 = vs2_obj.__enter__()
try:
    print(vs2.name)  # OK as well
finally:
    vs2_obj.__exit__(None, None, None)

但我猜有一些网站效应。

说明:上下文对象vs2_obj与当前上下文vs2本身存在差异。

这给出了输出

123
456

答案 1 :(得分:0)

另外,我编写了一个工具类来模仿matlab中的“with”语句。

helper.py:

background:url('image.jpg')

Matlab的:

class With(object):
    def __init__(self, obj):
        self._obj = obj
        self._p = self._obj.__enter__()

    def __del__(self):
        self._obj.__exit__(None, None, None)

    def get(self):
        return self._p