首页 > 解决方案 > 我们应该如何处理 name_scope 的自增呢?

问题描述

def foo():
    with tf.Session() as sess:
        with tf.name_scope("foo") as abso:
            print(abso)

for i in range(10):
    foo()

这是一个测试 tf 的简单代码name_scope。这段代码的输出是

foo/
foo_1/
foo_2/
foo_3/
foo_4/
foo_5/
foo_6/
foo_7/
foo_8/
foo_9/

通过哪种方式,片码的输出都是foo/s?

当我想让我的 tf 模型成为 webapp 时,这是一个问题。该应用程序可以正确处理第一个请求。但是当涉及到第二个或以后的请求时,它会尝试将图形以及所有变量与另一个name_scope(例如,foo_1)一起加载,并导致致命错误。

标签: pythontensorflow

解决方案


您可以存储该tf.name_scope方法创建的范围并重用它。例如:

scope = "foo"
def foo():
    global scope
    with tf.Session() as sess:
        with tf.name_scope(scope) as scope:
            print(scope)
for i in range(10):
    foo()

将打印

foo/
foo/
foo/
foo/
foo/
foo/
foo/
foo/
foo/
foo/

推荐阅读