【Tensorflow】Tensorflow一些數據IO、圖的運行相關函數

摘要:本系列主要對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) 使用該形式方法創建以上各種錯誤類


相關鏈接:

[1] 安裝Tensorflow(Linux ubuntu) http://blog.csdn.net/lenbow/article/details/51203526 
[2] ubuntu下CUDA編譯的GCC降級安裝 http://blog.csdn.net/lenbow/article/details/51596706 
[3] ubuntu手動安裝最新Nvidia顯卡驅動 http://blog.csdn.net/lenbow/article/details/51683783 
[4] Tensorflow的CUDA升級,以及相關配置 http://blog.csdn.net/lenbow/article/details/52118116 
[5] 基於gensim的Doc2Vec簡析 http://blog.csdn.net/lenbow/article/details/52120230 
[6] TensorFlow的分佈式學習框架簡介 http://blog.csdn.net/lenbow/article/details/52130565 
[7] Tensorflow一些常用基本概念與函數(1) http://blog.csdn.net/lenbow/article/details/52152766 
[8] Tensorflow一些常用基本概念與函數(2) http://blog.csdn.net/lenbow/article/details/52181159

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章