我已经意识到Tensorflow似乎在管理图形的方式上有一些时髦的东西。由于构建(和重建)模型非常繁琐,我决定将自定义模型包装在一个类中,以便我可以在其他地方轻松地重新实例化它。Tensorflow如何管理图形?
当我在训练和测试代码时(在原来的地方),它会工作的很好,但是在我加载图形变量的代码中,我会得到各种奇怪的错误 - 变量重定义和其他一切。这个(从我最后一个类似的问题)提示,一切都被称为两次。
做了跟踪TON后,它回到了我使用加载的代码的方式。它正在从一个类,有一个结构,像这样
class MyModelUser(object):
def forecast(self):
# .. build the model in the same way as in the training code
# load the model checkpoint
# call the "predict" function on the model
# manipulate the prediction and return it
然后在一些代码,使用MyModelUser
我有
def test_the_model(self):
model_user = MyModelUser()
print(model_user.forecast()) # 1
print(model_user.forecast()) # 2
和我(显然)有望看到两个预测这时候内使用被称为。相反,第一个预测被称为按预期工作,但第二个电话扔变量重用的TON ValueError异常的这些中的一个例子是:
ValueError: Variable weight_def/weights already exists, disallowed. Did you mean to set reuse=True in VarScope?
我设法通过增加一系列平息错误试图/使用get_variable
创建变量的块除外,然后在例外情况下,在范围上调用reuse_variables
,然后在名称上调用get_variable
。这带来了一套新的严重的错误,其中之一就是:
tensorflow.python.framework.errors.NotFoundError: Tensor name "weight_def/weights/Adam_1" not found in checkpoint files
一时心血来潮我说:“如果我的造型建筑物代码移到__init__
所以其只内置了一次?”
我的新机型的用户:
class MyModelUser(object):
def __init__(self):
# ... build the model in the same way as in the training code
# load the model checkpoint
def forecast(self):
# call the "predict" function on the model
# manipulate the prediction and return it
现在:
def test_the_model(self):
model_user = MyModelUser()
print(model_user.forecast()) # 1
print(model_user.forecast()) # 2
按预期工作,印花两大预测没有错误。这使我相信我也可以摆脱可变重用的东西。
我的问题是这样的:
这是为什么解决它?从理论上讲,应该在原始预测方法中每次都重新调整图形,因此它不应该创建多个图形。即使函数完成后,Tensorflow是否仍然保持图形?这就是为什么将创建代码移动到__init__
工作?这让我无望地感到困惑。