您好,登錄后才能下訂單哦!
有時我們希望在一個python的文件空間同時載入多個模型,例如 我們建立了10個CNN模型,然后我們又寫了一個預測類Predict,這個類會從已經保存好的模型restore恢復相應的圖結構以及模型參數。然后我們會創建10個Predict的對象Instance,每個Instance負責一個模型的預測。
Predict的核心為:
class Predict: def __init__(self....): 創建sess 創建恢復器tf.train.Saver 從恢復點恢復參數:tf.train.Saver.restore(...) def predict(self,...): sess.run(output,feed_dict={輸入})
如果我們直接輪流生成10個不同的Predict 對象的話,我們發現tensorflow是會報類似于下面的錯誤:
File "/home/jiangminghao/.local/lib/python3.5/site-packages/tensorflow/python/framework/errors_impl.py", line 466, in raise_exception_on_not_ok_status pywrap_tensorflow.TF_GetCode(status)) tensorflow.python.framework.errors_impl.InvalidArgumentError: Assign requires shapes of both tensors to match. lhs shape= [256,512] rhs shape= [640,512] [[Node: save/Assign_14 = Assign[T=DT_FLOAT, _class=["loc:@fullcont/Variable"], use_locking=true, validate_shape=true, _device="/job:localhost/replica:0/task:0/cpu:0"](fullcont/Variable, save/RestoreV2_14)]] During handling of the above exception, another exception occurred: Traceback (most recent call last): File "PREDICT_WITH_SPARK_DATAFLOW_WA.py", line 121, in <module> pre2=Predict(label=new_list[1]) File "PREDICT_WITH_SPARK_DATAFLOW_WA.py", line 47, in __init__ self.saver.restore(self.sess,self.ckpt.model_checkpoint_path) File "/home/jiangminghao/.local/lib/python3.5/site-packages/tensorflow/python/training/saver.py", line 1560, in restore {self.saver_def.filename_tensor_name: save_path}) File "/home/jiangminghao/.local/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 895, in run run_metadata_ptr) File "/home/jiangminghao/.local/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1124, in _run feed_dict_tensor, options, run_metadata) File "/home/jiangminghao/.local/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1321, in _do_run options, run_metadata) File "/home/jiangminghao/.local/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1340, in _do_call raise type(e)(node_def, op, message) tensorflow.python.framework.errors_impl.InvalidArgumentError: Assign requires shapes of both tensors to match. lhs shape= [256,512] rhs shape= [640,512]
關鍵就是:
Assign requires shapes of both tensors to match.意思是載入模型的時候 賦值失敗。主要是因為不同對象里面的不同sess使用了同一進程空間下的相同的默認圖graph。
正確的解決方法:
class Predict: def __init__(self....): self.graph=tf.Graph()#為每個類(實例)單獨創建一個graph with self.graph.as_default(): self.saver=tf.train.import_meta_graph(...)#創建恢復器 #注意!恢復器必須要在新創建的圖里面生成,否則會出錯。 self.sess=tf.Session(graph=self.graph)#創建新的sess with self.sess.as_default(): with self.graph.as_default(): self.saver.restore(self.sess,...)#從恢復點恢復參數 def predict(self,...): sess.run(output,feed_dict={輸入})
以上這篇Tensorflow 同時載入多個模型的實例講解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。