Tensorflow一些常用基本概念與函數(三)


摘要:本系列主要對tf的一些常用概念與方法進行描述。本文主要針對tensorflow的數據IO、圖的運行等相關函數進行講解。為‘Tensorflow一些常用基本概念與函數’系列之三。

1、序言

本文所講的內容主要為以下相關函數:

操作組 操作
Data IO (Python functions) TFRecordWrite,rtf_record_iterator
Running Graphs Session management,Error classes

2、tf函數

2.1 數據IO {Data IO (Python functions)}

一個TFRecords 文件為一個字符串序列。這種格式並非隨機獲取,它比較適合大規模的數據流,而不太適合需要快速分區或其他非序列獲取方式。

數據IO {Data IO (Python functions)}

操作 描述
class tf.python_io.TFRecordWriter 一個用於將記錄(records)寫入TFRecords文件的類
tf.python_io.TFRecordWriter.__init__(path, options=None) 打開文件路徑,並創建一個TFRecordWriter以供寫入
tf.python_io.TFRecordWriter.write(record) 將一個字符串records寫入文件中
tf.python_io.TFRecordWriter.close() 關閉文件
tf.python_io.tf_record_iterator(path, options=None) 從TFRecords文件中讀取記錄的迭代器

2.2 運行圖(Running Graphs)

會話管理 (Session management)

操作 描述
class tf.Session 運行TF操作的類,
一個Session對象將操作節點op封裝在一定的環境內運行,
同時tensor對象將被計算求值
tf.Session.__init__(target=”, graph=None, config=None) 創建一個新的會話
tf.Session.run(fetches, feed_dict=None, 
options=None, run_metadata=None)
運行fetches中的操作節點並求其值
tf.Session.close() 關閉會話
tf.Session.graph 返回加載值該會話的圖(graph)
tf.Session.as_default() 設置該對象為默認會話,並返回一個上下文管理器
tf.Session.reset(target, containers=None, config=None) 重設target的資源容器,並關閉所有連接的會話
在0.10版本該功能僅應用在分布會話中
target:為執行引擎所連接的目標,其包含有資源容器,
該資源容器分布在同一個集群的所有works上
class tf.InteractiveSession 使用在交互式上下文環境的tf會話,比如shell,ipython
tf.InteractiveSession.close() 關閉一個InteractiveSession
tf.get_default_session() 返回當前線程的默認會話

tf.Session

#一個簡單的tf.Session例子 # 建立一個graph. a = tf.constant(5.0) b = tf.constant(6.0) c = a * b # 將graph載入到一個會話session中 sess = tf.Session() # 計算tensor `c`. print(sess.run(c)) 

 

 

#一個會話可能會占用一些資源,比如變量、隊列和讀取器(reader)。釋放這些不再使用的資源非常重要。 #使用close()方法關閉會話,或者使用上下文管理器,釋放資源。 # 使用`close()`方法. sess = tf.Session() sess.run(...) sess.close() # 使用上下文管理器 with tf.Session() as sess: sess.run(...) 

 

 

tf.Session()的變量設置, ConfigProto protocol buffer為會話提供了不同的配置選項。比如,創建一個會話,對設備布局使用軟約束條件,以及對分布

# Launch the graph in a session that allows soft device placement and # logs the placement decisions. sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True)) 

 

 

tf.Session.run


 a = tf.constant([10, 20]) b = tf.constant([1.0, 2.0]) # 'fetches' 可以為單個數 v = session.run(a) # v is the numpy array [10, 20] # 'fetches' 可以為一個list. v = session.run([a, b]) # v a Python list with 2 numpy arrays: the numpy array [10, 20] and the # 1-D array [1.0, 2.0] # 'fetches' 可以是 lists, tuples, namedtuple, dicts中的任意: MyData = collections.namedtuple('MyData', ['a', 'b']) v = session.run({'k1': MyData(a, b), 'k2': [b, a]}) # v 為一個dict,並有 # 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]. 

 

 

tf.Session.as_default() 
使用關鍵字with指定會話, 可以在會話中執行Operation.run()Tensor.eval(),以得到運行的tensor結果

c = tf.constant(..)
sess = tf.Session()

with sess.as_default(): assert tf.get_default_session() is sess print(c.eval()) 

 

 

使用函數tf.get_default_session()來得到當前默認的會話 
需要注意的是,退出該as_default上下文管理器時,並沒有關閉該會話(session ),必須明確的關閉會話

c = tf.constant(...)
sess = tf.Session()
with sess.as_default(): print(c.eval()) # ... with sess.as_default(): print(c.eval()) #關閉會話 sess.close() #使用 with tf.Session()方式可以創建並自動關閉會話

 

 

tf.InteractiveSession

sess = tf.InteractiveSession()
a = tf.constant(5.0) b = tf.constant(6.0) c = a * b # 我們直接使用'c.eval()' 而沒有通過'sess' print(c.eval()) sess.close()

 

 

以上的例子,在非交互會話的版本中為,

a = tf.constant(5.0) b = tf.constant(6.0) c = a * b with tf.Session(): # We can also use 'c.eval()' here. print(c.eval())

 

 

ABC

錯誤類 (Error classes)

 

操作 描述
class tf.OpError 一個基本的錯誤類型,在當TF執行失敗時候報錯
tf.OpError.op 返回執行失敗的操作節點,
有的操作如Send或Recv可能不會返回,那就要用用到node_def方法
tf.OpError.node_def 以NodeDef proto形式表示失敗的op
tf.OpError.error_code 描述該錯誤的整數錯誤代碼
tf.OpError.message 返回錯誤信息
class tf.errors.CancelledError 當操作或者階段唄取消時候報錯
class tf.errors.UnknownError 未知錯誤類型
class tf.errors.InvalidArgumentError 在接收到非法參數時候報錯
class tf.errors.NotFoundError 當發現不存在所請求的一個實體時候,比如文件或目錄
class tf.errors.AlreadyExistsError 當創建的實體已經存在的時候報錯
class tf.errors.PermissionDeniedError 沒有執行權限做某操作的時候報錯
class tf.errors.ResourceExhaustedError 資源耗盡時報錯
class tf.errors.FailedPreconditionError 系統沒有條件執行某個行為時候報錯
class tf.errors.AbortedError 操作中止時報錯,常常發生在並發情形
class tf.errors.OutOfRangeError 超出范圍報錯
class tf.errors.UnimplementedError 某個操作沒有執行時報錯
class tf.errors.InternalError 當系統經歷了一個內部錯誤時報出
class tf.errors.DataLossError 當出現不可恢復的錯誤
例如在運行 tf.WholeFileReader.read()讀取整個文件的同時文件被刪減
tf.errors.XXXXX.__init__(node_def, op, message) 使用該形式方法創建以上各種錯誤類


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM