Tensorflow運行程序報錯 FailedPreconditionError
1 FailedPreconditionError錯誤現象
在運行tensorflow時出現報錯,報錯語句如下:
FailedPreconditionError (see above for traceback): Attempting to use uninitialized value Variable
[[Node: Variable/read = _MklIdentity[T=DT_FLOAT, _kernel="MklOp", _device="/job:localhost/replica:0/task:0/device:CPU:0"](Variable, DMT/_0)]]
對報錯原因進行直白翻譯(信、雅、達精度嚴重缺失):
條件預處理時失敗錯誤(參看上面的回溯):嘗試使用未初始化的值變量。
2 FailedPreconditionError錯誤淺析
2.1 FailedPreconditionError的淺析
查看錯誤類源代碼:
class FailedPreconditionError(OpError): """Operation was rejected because the system is not in a state to execute it. This exception is most commonly raised when running an operation that reads a @{tf.Variable} before it has been initialized. @@__init__""" def __init__(self, node_def, op, message): """Creates a `FailedPreconditionError`.""" super(FailedPreconditionError, self).__init__(node_def, op, message, FAILED_PRECONDITION)
註釋意思可理解為:
因為系統未處於執行狀態,所以操作被拒絕。
在@ {tf.Variable}初始化前運行讀取操作時,通常會引發此異常。
2.2 global_variables_initializer的源代碼
查看global_variables_initializer函數的源代碼
def global_variables_initializer(): """Returns an Op that initializes global variables. This is just a shortcut for `variables_initializer(global_variables())` Returns: An Op that initializes global variables in the graph. """ if context.executing_eagerly(): return control_flow_ops.no_op(name="global_variables_initializer") return variables_initializer(global_variables())
溯源,查看variable_initializer函數源代碼。
def variables_initializer(var_list, name="init"): """Returns an Op that initializes a list of variables. After you launch the graph in a session, you can run the returned Op to initialize all the variables in `var_list`. This Op runs all the initializers of the variables in `var_list` in parallel. Calling `initialize_variables()` is equivalent to passing the list of initializers to `Group()`. If `var_list` is empty, however, the function still returns an Op that can be run. That Op just has no effect. Args: var_list: List of `Variable` objects to initialize. name: Optional name for the returned operation. Returns: An Op that run the initializers of all the specified variables. """ if var_list and not context.executing_eagerly(): return control_flow_ops.group(*[v.initializer for v in var_list], name=name) return control_flow_ops.no_op(name=name)
查看global_variables()函數源代碼。
def global_variables(scope=None): """Returns global variables. Global variables are variables that are shared across machines in a distributed environment. The `Variable()` constructor or `get_variable()` automatically adds new variables to the graph collection `GraphKeys.GLOBAL_VARIABLES`. This convenience function returns the contents of that collection. An alternative to global variables are local variables. See @{tf.local_variables} Args: scope: (Optional.) A string. If supplied, the resulting list is filtered to include only items whose `name` attribute matches `scope` using `re.match`. Items without a `name` attribute are never returned if a scope is supplied. The choice of `re.match` means that a `scope` without special tokens filters by prefix. Returns: A list of `Variable` objects. """ return ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES, scope)
2.3 全局變量初始化分析
2.3.1 變量
Tensorflow 變量是表示程序處理的共享持久狀態的最佳方法。
我們通過tf.Variable類操作變量。tf.Variable表示可通過對其運行操作來改變其值的張量。
與tf.Tensor對象不同,tf.Variable存在於單個tf.Session().run()調用的上下文之外。
在TensorFlow內部,tf.Variable會存儲持久性張量。具體operation( op )允許您讀取和修改張量的值。這些修改在多個tf.Session()之間是可見的,因此對於一個tf.Variable,多個工作器可以看到相同的值。
2.3.2 變量集合
由於 TensorFlow 程序的未連接部分可能需要創建變量,因此能有一種方式訪問所有變量有時十分受用。為此,TensorFlow 提供了集合,它們是張量或其他對象(如 tf.Variable
實例)的命名列表。
默認情況下,每個 tf.Variable
都放置在以下兩個集合中:
tf.GraphKeys.GLOBAL_VARIABLES
- 可以在多臺設備間共享的變量,tf.GraphKeys.TRAINABLE_VARIABLES
- TensorFlow 將計算其梯度的變量。
如果您不希望變量可訓練,可以將其添加到 tf.GraphKeys.LOCAL_VARIABLES
集合中。
2.3.3 初始化變量
變量必須先初始化後才可使用。
如果您在低級別 TensorFlow API 中進行編程(即您在顯式創建自己的圖和會話),則必須明確初始化變量。tf.contrib.slim
、tf.estimator.Estimator
和 Keras
等大多數高級框架在訓練模型前會自動為您初始化變量。
顯式初始化在其他方面很有用。它允許您在從檢查點重新加載模型時不用重新運行潛在資源消耗大的初始化器,並允許在分布式設置中共享隨機初始化的變量時具有確定性。
要在訓練開始前一次性初始化所有可訓練變量,請調用 tf.global_variables_initializer()
。此函數會返回一個操作,負責初始化 tf.GraphKeys.GLOBAL_VARIABLES
集合中的所有變量。運行此操作會初始化所有變量。例如:
session.run(tf.global_variables_initializer()) # Now all variables are initialized.
如果您確實需要自行初始化變量,則可以運行變量的初始化器操作。例如:
session.run(my_variable.initializer)
您可以查詢哪些變量尚未初始化。例如,以下代碼會打印所有尚未初始化的變量名稱:
print(session.run(tf.report_uninitialized_variables()))
請註意,默認情況下,tf.global_variables_initializer
不會指定變量的初始化順序。因此,如果變量的初始值取決於另一變量的值,那麽很有可能會出現錯誤。任何時候,如果您在並非所有變量都已初始化的上下文中使用某個變量值(例如在初始化某個變量時使用另一變量的值),最好使用 variable.initialized_value()
,而非 variable
:
v = tf.get_variable("v", shape=(), initializer=tf.zeros_initializer()) w = tf.get_variable("w", initializer=v.initialized_value() + 1)
具體參考 Tensorflow的官方信息 --> 變量 https://www.tensorflow.org/programmers_guide/variables
備註:
在2017年03月02日之前,全局變量初始化函數initialize_all_variables();之後為global_variables_initializer()函數。
參考
處理FailedPreconditionError、該文針對FailedPreconditionError錯誤函數進行解讀
TensorFlow定義錯誤的異常類型(詳細)進入該文直接搜索FailedPreconditionError函數,可以看到源代碼段
變量初始化的意義 該文從C/C++程序中的棧和堆上來說存儲並采用示例分析證明
具體參考 Tensorflow的官方信息 --> 變量 https://www.tensorflow.org/programmers_guide/variables
tf.global_variables_initializer:https://devdocs.io/tensorflow~python/tf/global_variables_initializer
tensorflow/tensorflow/python/ops/variables.py:https://github.com/tensorflow/tensorflow/blob/r1.8/tensorflow/python/ops/variables.py
tensorflow中的參數初始化方法
FailedPreconditionError tensorflow
Tensorflow運行程序報錯 FailedPreconditionError