我可以在没有"with"声明的情况下致电tf.variable_scope吗?



我想在matlab中调用tensorflow的python API(见 https://www.mathworks.com/help/matlab/matlab_external/call-python-from-matlab.html(。 matlab 不支持 "with" 语句。 如果没有"with"语句,我无法创建tf.variable_scope。 我已经尝试了下面的两个代码,但都不起作用。 有什么解决办法吗?

蟒:

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'

矩阵:

vs = py.tensorflow.variable_scope('GRAPH', pyargs('reuse', py.tensorflow.AUTO_REUSE));
vs.name  % No appropriate method, property, or field 'name' for class 'py.tensorflow.python.ops.variable_scope.variable_scope'.

你可以重写 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

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

helper.py:

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

矩阵:

with_vs = py.helper.With(py.tensorflow.variable_scope('X'));
with_vs.get().name
...
clear with_vs;

最新更新