python tensorflow tf.Session().run()函数(运行操作并评估“fetches”中的张量)
生活随笔
收集整理的這篇文章主要介紹了
python tensorflow tf.Session().run()函数(运行操作并评估“fetches”中的张量)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
參考文章:TensorFlow-sess.run()
當我們構建完圖(可能是我們pre_process后生成的圖片?NoNoNo,它只是指tensorflow框架的一種設計理念——計算流圖)后,需要在一個會話中啟動圖,啟動的第一步是創建一個Session對象。
為了取回(Fetch)操作的輸出內容, 可以在使用 Session 對象的 run()調用執行圖時,傳入一些 tensor, 這些 tensor 會幫助你取回結果。
在python語言中,返回的tensor是numpy ndarray對象。
在執行sess.run()時,tensorflow并不是計算了整個圖,只是計算了與想要fetch 的值相關的部分。
from tensorflow\python\client\session.py
def run(self, fetches, feed_dict=None, options=None, run_metadata=None):"""Runs operations and evaluates tensors in `fetches`.運行操作并評估“fetches”中的張量。This method runs one "step" of TensorFlow computation, byrunning the necessary graph fragment to execute every `Operation`and evaluate every `Tensor` in `fetches`, substituting the values in`feed_dict` for the corresponding input values.此方法運行TensorFlow計算的一個“步驟”,方法是運行必要的圖形片段以執行每個“操作”并評估“fetches”中的每個“ Tensor”,然后將“ feed_dict”中的值替換為相應的輸入值。The `fetches` argument may be a single graph element, or an arbitrarilynested list, tuple, namedtuple, dict, or OrderedDict containing graphelements at its leaves. A graph element can be one of the following types:“ fetches”參數可以是單個圖形元素,也可以是在其葉子處包含圖形元素的任意嵌套的列表,元組,namedtuple,dict或OrderedDict。 圖元素可以是以下類型之一:* An `tf.Operation`.The corresponding fetched value will be `None`.* A `tf.Tensor`.The corresponding fetched value will be a numpy ndarray containing thevalue of that tensor.* A `tf.SparseTensor`.The corresponding fetched value will be a`tf.SparseTensorValue`containing the value of that sparse tensor.* A `get_tensor_handle` op. The corresponding fetched value will be anumpy ndarray containing the handle of that tensor.* A `string` which is the name of a tensor or operation in the graph.*`tf.Operation`。相應的獲取值將為“無”。*`tf.Tensor`。相應的獲取值將是一個numpy ndarray,其中包含張量的值。*`tf.SparseTensor`。相應的獲取值將是tf.SparseTensorValue包含那個稀疏張量的值。*`get_tensor_handle`操作。 相應的獲取值將是包含該張量的句柄的numpy ndarray。*字符串,是圖中張量或操作的名稱。The value returned by `run()` has the same shape as the `fetches` argument,where the leaves are replaced by the corresponding values returned byTensorFlow.run()返回的值與fetches參數具有相同的形狀,其中葉子被TensorFlow返回的相應值替換。Example:```pythona = tf.constant([10, 20])b = tf.constant([1.0, 2.0])# 'fetches' can be a singleton “fetches”可以是單例v = session.run(a)# v is the numpy array [10, 20] v是numpy數組[10,20]# 'fetches' can be a list. “fetches”可以是一個列表。v = session.run([a, b])# v is a Python list with 2 numpy arrays: the 1-D array [10, 20] and the# 1-D array [1.0, 2.0]# v是具有2個numpy數組的Python列表:一維數組[10,20]和一維數組[1.0,2.0]# 'fetches' can be arbitrary lists, tuples, namedtuple, dicts:# “fetches”可以是任意列表,元組,namedtuple,字典:MyData = collections.namedtuple('MyData', ['a', 'b'])v = session.run({'k1': MyData(a, b), 'k2': [b, a]})# v is a dict with# v['k1'] is a MyData namedtuple with 'a' (the numpy array [10, 20]) and# 'b' (the numpy array [1.0, 2.0])# v['k2'] is a list with the numpy array [1.0, 2.0] and the numpy array# [10, 20].```The optional `feed_dict` argument allows the caller to overridethe value of tensors in the graph. Each key in `feed_dict` can beone of the following types:可選的feed_dict參數允許調用者覆蓋圖中的張量值。 feed_dict中的每個鍵可以是以下類型之一:* If the key is a `tf.Tensor`, thevalue may be a Python scalar, string, list, or numpy ndarraythat can be converted to the same `dtype` as thattensor. Additionally, if the key is a`tf.placeholder`, the shape ofthe value will be checked for compatibility with the placeholder.* If the key is a`tf.SparseTensor`,the value should be a`tf.SparseTensorValue`.* If the key is a nested tuple of `Tensor`s or `SparseTensor`s, the valueshould be a nested tuple with the same structure that maps to theircorresponding values as above.*如果鍵是`tf.Tensor`,則值可以是Python標量,字符串,列表或numpy ndarray,可以將其轉換為與該張量相同的`dtype`。 此外,如果鍵是`tf.placeholder`,則將檢查值的形狀與占位符的兼容性。*如果密鑰是`tf.SparseTensor`,則該值應為`tf.SparseTensorValue`。*如果鍵是`Tensor`或`SparseTensor`的嵌套元組,則該值應是具有與上述對應值對應的結構相同的嵌套元組。Each value in `feed_dict` must be convertible to a numpy array of the dtypeof the corresponding key.feed_dict中的每個值都必須可轉換為對應鍵dtype的numpy數組。The optional `options` argument expects a [`RunOptions`] proto. The optionsallow controlling the behavior of this particular step (e.g. turning tracingon).可選的`options`參數需要一個[`RunOptions`]原型。 這些選項允許控制此特定步驟的行為(例如,打開跟蹤)。The optional `run_metadata` argument expects a [`RunMetadata`] proto. Whenappropriate, the non-Tensor output of this step will be collected there. Forexample, when users turn on tracing in `options`, the profiled info will becollected into this argument and passed back.可選的`run_metadata`參數需要一個[`RunMetadata`]原型。 適當時,將在此收集此步驟的非Tensor輸出。 例如,當用戶打開“選項”中的跟蹤時,配置文件信息將收集到此參數中并傳遞回去。Args:fetches: A single graph element, a list of graph elements,or a dictionary whose values are graph elements or lists of graphelements (described above).一個圖元素,一個圖元素列表或一個字典,其值為圖元素或圖元素列表(如上所述)。feed_dict: A dictionary that maps graph elements to values(described above).將圖形元素映射到值的字典(如上所述)。options: A [`RunOptions`] protocol buffer 一個[`RunOptions`]協議緩沖區run_metadata: A [`RunMetadata`] protocol buffer一個[`RunMetadata`]協議緩沖區Returns:Either a single value if `fetches` is a single graph element, ora list of values if `fetches` is a list, or a dictionary with thesame keys as `fetches` if that is a dictionary (described above).Order in which `fetches` operations are evaluated inside the callis undefined.如果fetches是單個圖形元素,則為單個值;如果fetches為列表,則為值列表;如果字典是具有與fetches相同鍵的字典,則為字典(如上所述)。 在調用內部評估“fetches”操作的順序是不確定的。Raises:RuntimeError: If this `Session` is in an invalid state (e.g. has beenclosed).RuntimeError:如果此“會話”處于無效狀態(例如已關閉)。TypeError: If `fetches` or `feed_dict` keys are of an inappropriate type.TypeError:如果`fetches`或`feed_dict`鍵的類型不合適。ValueError: If `fetches` or `feed_dict` keys are invalid or refer to a`Tensor` that doesn't exist.ValueError:如果“fetches”或“ feed_dict”鍵無效或引用了不存在的“張量”。"""options_ptr = tf_session.TF_NewBufferFromString(compat.as_bytes(options.SerializeToString())) if options else Nonerun_metadata_ptr = tf_session.TF_NewBuffer() if run_metadata else Nonetry:result = self._run(None, fetches, feed_dict, options_ptr,run_metadata_ptr)if run_metadata:proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)run_metadata.ParseFromString(compat.as_bytes(proto_data))finally:if run_metadata_ptr:tf_session.TF_DeleteBuffer(run_metadata_ptr)if options:tf_session.TF_DeleteBuffer(options_ptr)return result參考文章:對比tensorflow查看向量Tensor的兩種方法(急切執行tf.enable_eager_execution()和tf.Session.run())
總結
以上是生活随笔為你收集整理的python tensorflow tf.Session().run()函数(运行操作并评估“fetches”中的张量)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: tensorflow 1.11.0 AP
- 下一篇: tensorflow1.11.0 tf.