我已經意識到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__
工作?這讓我無望地感到困惑。