日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

TensorFlow(五)常用函数与基本操作

發布時間:2023/12/15 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 TensorFlow(五)常用函数与基本操作 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

tensorflow的基本運作

1、tensorflow的基本運作

2、tf函數

TensorFlow 將圖形定義轉換成分布式執行的操作, 以充分利用可用的計算資源 (如 CPU 或 GPU。一般你不需要顯式指定使用 CPU 還是 GPU,TensorFlow 能自動檢測。 如果檢測到 GPU, TensorFlow 會盡可能地利用找到的第一個 GPU 來執行操作. 并行計算能讓代價大的算法計算加速執行,TensorFlow也在實現上對復雜操作進行了有效的改進。 大部分核相關的操作都是設備相關的實現,比如GPU。
  • 1
  • 2
  • 3
操作組操作
Building GraphsCore graph data structures,Tensor types,Utility functions
Inputs and ReadersPlaceholders,Readers,Converting,Queues,Input pipeline

2.1 建立圖(Building Graphs)

本節主要介紹建立tensorflow圖的相關類或函數

* 核心圖的數據結構(Core graph data structures)

tf.Graph

操作描述
class tf.Graphtensorflow中的計算以圖數據流的方式表示
一個圖包含一系列表示計算單元的操作對象
以及在圖中流動的數據單元以tensor對象表現
tf.Graph.__init__()建立一個空圖
tf.Graph.as_default()一個將某圖設置為默認圖,并返回一個上下文管理器
如果不顯式添加一個默認圖,系統會自動設置一個全局的默認圖。
所設置的默認圖,在模塊范圍內所定義的節點都將默認加入默認圖中
tf.Graph.as_graph_def
(from_version=None, add_shapes=False)
返回一個圖的序列化的GraphDef表示
序列化的GraphDef可以導入至另一個圖中(使用 import_graph_def())
或者使用C++ Session API
tf.Graph.finalize()完成圖的構建,即將其設置為只讀模式
tf.Graph.finalized返回True,如果圖被完成
tf.Graph.control_dependencies(control_inputs)定義一個控制依賴,并返回一個上下文管理器
with g.control_dependencies([a, b, c]):
# `d` 和 `e` 將在 `a`, `b`, 和`c`執行完之后運行.
d = …
e = …
tf.Graph.device(device_name_or_function)定義運行圖所使用的設備,并返回一個上下文管理器
with g.device('/gpu:0'): ...
with g.device('/cpu:0'): ...
tf.Graph.name_scope(name)為節點創建層次化的名稱,并返回一個上下文管理器
tf.Graph.add_to_collection(name, value)將value以name的名稱存儲在收集器(collection)中
tf.Graph.get_collection(name, scope=None)根據name返回一個收集器中所收集的值的列表
tf.Graph.as_graph_element
(obj, allow_tensor=True, allow_operation=True)
返回一個圖中與obj相關聯的對象,為一個操作節點或者tensor數據
tf.Graph.get_operation_by_name(name)根據名稱返回操作節點
tf.Graph.get_tensor_by_name(name)根據名稱返回tensor數據
tf.Graph.get_operations()返回圖中的操作節點列表
tf.Graph.gradient_override_map(op_type_map)用于覆蓋梯度函數的上下文管理器
#class tf.Graph #tensorflow運行時需要設置默認的圖 g = tf.Graph() with g.as_default():# Define operations and tensors in `g`.c = tf.constant(30.0)assert c.graph is g##也可以使用tf.get_default_graph()獲得默認圖,也可在基礎上加入節點或子圖 c = tf.constant(4.0) assert c.graph is tf.get_default_graph()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
#tf.Graph.as_default #以下兩段代碼功能相同 #1、使用Graph.as_default(): g = tf.Graph() with g.as_default():c = tf.constant(5.0)assert c.graph is g#2、構造和設置為默認 with tf.Graph().as_default() as g:c = tf.constant(5.0)assert c.graph is g
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
#tf.Graph.control_dependencies(control_inputs) # 錯誤代碼 def my_func(pred, tensor):t = tf.matmul(tensor, tensor)with tf.control_dependencies([pred]):# 乘法操作(op)沒有創建在該上下文,所以沒有被加入依賴控制return t# 正確代碼 def my_func(pred, tensor):with tf.control_dependencies([pred]):# 乘法操作(op)創建在該上下文,所以被加入依賴控制中#執行完pred之后再執行matmulreturn tf.matmul(tensor, tensor)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
# tf.Graph.name_scope(name) # 一個圖中包含有一個名稱范圍的堆棧,在使用name_scope(...)之后,將壓(push)新名稱進棧中, #并在下文中使用該名稱 with tf.Graph().as_default() as g:c = tf.constant(5.0, name="c")assert c.op.name == "c"c_1 = tf.constant(6.0, name="c")assert c_1.op.name == "c_1"# Creates a scope called "nested"with g.name_scope("nested") as scope:nested_c = tf.constant(10.0, name="c")assert nested_c.op.name == "nested/c"# Creates a nested scope called "inner".with g.name_scope("inner"):nested_inner_c = tf.constant(20.0, name="c")assert nested_inner_c.op.name == "nested/inner/c"# Create a nested scope called "inner_1".with g.name_scope("inner"):nested_inner_1_c = tf.constant(30.0, name="c")assert nested_inner_1_c.op.name == "nested/inner_1/c"# Treats `scope` as an absolute name scope, and# switches to the "nested/" scope.with g.name_scope(scope):nested_d = tf.constant(40.0, name="d")assert nested_d.op.name == "nested/d"with g.name_scope(""):e = tf.constant(50.0, name="e")assert e.op.name == "e"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

tf.Operation

操作描述
class tf.Operation代表圖中的一個節點,用于計算tensors數據
該類型將由python節點構造器產生(比如tf.matmul())
或者Graph.create_op()
例如c = tf.matmul(a, b)創建一個Operation類
為類型為”MatMul”,輸入為’a’,’b’,輸出為’c’的操作類
tf.Operation.name操作節點(op)的名稱
tf.Operation.type操作節點(op)的類型,比如”MatMul”
tf.Operation.inputs
tf.Operation.outputs
操作節點的輸入與輸出
tf.Operation.control_inputs操作節點的依賴
tf.Operation.run(feed_dict=None, session=None)在會話(Session)中運行該操作
tf.Operation.get_attr(name)獲取op的屬性值

tf.Tensor

操作描述
class tf.Tensor表示一個由操作節點op產生的值,
TensorFlow程序使用tensor數據結構來代表所有的數據,
計算圖中, 操作間傳遞的數據都是 tensor,一個tensor是一個符號handle,
里面并沒有表示實際數據,而相當于數據流的載體
tf.Tensor.dtypetensor中數據類型
tf.Tensor.name該tensor名稱
tf.Tensor.value_index該tensor輸出外op的index
tf.Tensor.graph該tensor所處在的圖
tf.Tensor.op產生該tensor的op
tf.Tensor.consumers()返回使用該tensor的op列表
tf.Tensor.eval(feed_dict=None, session=None)在會話中求tensor的值
需要使用with sess.as_default()或者 eval(session=sess)
tf.Tensor.get_shape()返回用于表示tensor的shape的類TensorShape
tf.Tensor.set_shape(shape)更新tensor的shape
tf.Tensor.device設置計算該tensor的設備
#tf.Tensor.get_shape() c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) print(c.get_shape()) ==> TensorShape([Dimension(2), Dimension(3)])
  • 1
  • 2
  • 3
  • 4
#現在有個用于圖像處理的tensor->image print(image.get_shape()) ==> TensorShape([Dimension(None), Dimension(None), Dimension(3)]) # 假如我們知道數據集中圖像尺寸為28 x 28,那么可以設置 image.set_shape([28, 28, 3]) print(image.get_shape()) ==> TensorShape([Dimension(28), Dimension(28), Dimension(3)])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

* tensor類型(Tensor types)

tf.DType

操作描述
class tf.DType數據類型主要包含
tf.float16,tf.float16,tf.float32,tf.float64,
tf.bfloat16,tf.complex64,tf.complex128,
tf.int8,tf.uint8,tf.uint16,tf.int16,tf.int32,
tf.int64,tf.bool,tf.string
tf.DType.is_compatible_with(other)判斷other的數據類型是否將轉變為該DType
tf.DType.name數據類型名稱
tf.DType.base_dtype返回該DType的基礎DType,而非參考的數據類型(non-reference)
tf.DType.as_ref返回一個基于DType的參考數據類型
tf.DType.is_floating判斷是否為浮點類型
tf.DType.is_complex判斷是否為復數
tf.DType.is_integer判斷是否為整數
tf.DType.is_unsigned判斷是否為無符號型數據
tf.DType.as_numpy_dtype返回一個基于DType的numpy.dtype類型
tf.DType.max
tf.DType.min
返回這種數據類型能表示的最大值及其最小值
tf.as_dtype(type_value)返回由type_value轉變得的相應tf數據類型


* 通用函數(Utility functions)

操作描述
tf.device(device_name_or_function)基于默認的圖,其功能便為Graph.device()
tf.container(container_name)基于默認的圖,其功能便為Graph.container()
tf.name_scope(name)基于默認的圖,其功能便為 Graph.name_scope()
tf.control_dependencies(control_inputs)基于默認的圖,其功能便為Graph.control_dependencies()
tf.convert_to_tensor
(value, dtype=None, name=None, as_ref=False)
將value轉變為tensor數據類型
tf.get_default_graph()返回返回當前線程的默認圖
tf.reset_default_graph()清除默認圖的堆棧,并設置全局圖為默認圖
tf.import_graph_def(graph_def, input_map=None,
return_elements=None, name=None, op_dict=None,
producer_op_list=None)
將graph_def的圖導入到python中

* 圖收集(Graph collections)

操作描述
tf.add_to_collection(name, value)基于默認的圖,其功能便為Graph.add_to_collection()
tf.get_collection(key, scope=None)基于默認的圖,其功能便為Graph.get_collection()

* 定義新操作節點(Defining new operations)

tf.RegisterGradient

操作描述
class tf.RegisterGradient返回一個用于寄存op類型的梯度函數的裝飾器
tf.NoGradient(op_type)設置操作節點類型op_type的節點沒有指定的梯度
class tf.RegisterShape返回一個用于寄存op類型的shape函數的裝飾器
class tf.TensorShape表示tensor的shape
tf.TensorShape.merge_with(other)與other合并shape信息,返回一個TensorShape類
tf.TensorShape.concatenate(other)與other的維度相連結
tf.TensorShape.ndims返回tensor的rank
tf.TensorShape.dims返回tensor的維度
tf.TensorShape.as_list()以list的形式返回tensor的shape
tf.TensorShape.is_compatible_with(other)判斷shape是否為兼容
TensorShape(None)與其他任何shape值兼容
class tf.Dimension
tf.Dimension.is_compatible_with(other)判斷dims是否為兼容
tf.Dimension.merge_with(other)與other合并dims信息
tf.op_scope(values, name, default_name=None)在python定義op時,返回一個上下文管理器
#tf.RegisterGradient #該裝飾器只使用于定義一個新的op類型時候,如果一個op有m個輸入,n個輸出。那么該梯度函數應該設置原始的 #操作類型,以及n個Tensor對象(表示每一個op輸出的梯度),以及m個對象(表示每一個op輸入的偏梯度) #以操作節點類型為'Sub'為例,兩輸入為x,y。為一個輸出x-y @tf.RegisterGradient("Sub") def _sub_grad(unused_op, grad):return grad, tf.neg(grad)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
#tf.op_scope #定義一個名稱為my_op的python操作節點op def my_op(a, b, c, name=None):with tf.op_scope([a, b, c], name, "MyOp") as scope:a = tf.convert_to_tensor(a, name="a")b = tf.convert_to_tensor(b, name="b")c = tf.convert_to_tensor(c, name="c")# Define some computation that uses `a`, `b`, and `c`.return foo_op(..., name=scope)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9


2.2 輸入和讀取器(Inputs and Readers)

本節主要介紹tensorflow中數據的讀入相關類或函數


* 占位符(Placeholders)

tf提供一種占位符操作,在執行時需要為其提供數據data。

操作描述
tf.placeholder(dtype, shape=None, name=None)為一個tensor插入一個占位符
eg:x = tf.placeholder(tf.float32, shape=(1024, 1024))
tf.placeholder_with_default(input, shape, name=None)當輸出沒有fed時,input通過一個占位符op
tf.sparse_placeholder(dtype, shape=None, name=None)為一個稀疏tensor插入一個占位符

* 讀取器(Readers)

tf提供一系列讀取各種數據格式的類。對于多文件輸入,可以使用函數tf.train.string_input_producer,該函數將創建一個保持文件的FIFO隊列,以供reader使用。或者如果輸入的這些文件名有相雷同的字符串,也可以使用函數tf.train.match_filenames_once。

操作描述
class tf.ReaderBase不同的讀取器類型的基本類
tf.ReaderBase.read(queue, name=None)返回下一個記錄對(key, value),queue為tf文件隊列FIFOQueue
tf.ReaderBase.read_up_to(queue, num_records, name=None)返回reader產生的num_records對(key, value)
tf.ReaderBase.reader_ref返回應用在該reader上的Op
tf.ReaderBase.reset(name=None)恢復reader為初始狀態
tf.ReaderBase.restore_state(state, name=None)恢復reader為之前的保存狀態state
tf.ReaderBase.serialize_state(name=None)返回一個reader解碼后產生的字符串tansor
class tf.TextLineReader
tf.TextLineReader.num_records_produced(name=None)返回reader已經產生的記錄(records )數目
tf.TextLineReader.num_work_units_completed(name=None)返回該reader已經完成的處理的work數目
tf.TextLineReader.read(queue, name=None)返回reader所產生的下一個記錄對 (key, value),該reader可以限定新產生輸出的行數
tf.TextLineReader.reader_ref返回應用在該reader上的Op
tf.TextLineReader.reset(name=None)恢復reader為初始狀態
tf.TextLineReader.restore_state(state, name=None)恢復reader為之前的保存狀態state
tf.TextLineReader.serialize_state(name=None)返回一個reader解碼后產生的字符串tansor
class tf.WholeFileReader一個閱讀器,讀取整個文件,返回文件名稱key,以及文件中所有的內容value,該類的方法同上,不贅述
class tf.IdentityReader一個reader,以key和value的形式,輸出一個work隊列。該類其他方法基本同上
class tf.TFRecordReader讀取TFRecord格式文件的reader。該類其他方法基本同上
class tf.FixedLengthRecordReader輸出

* 數據轉換(Converting)

tf提供一系列方法將各種格式數據轉換為tensor表示。

操作描述
tf.decode_csv(records, record_defaults, field_delim=None, name=None)將csv轉換為tensor,與tf.TextLineReader搭配使用
tf.decode_raw(bytes, out_type, little_endian=None, name=None)將bytes轉換為一個數字向量表示,bytes為一個字符串類型的tensor與函數 tf.FixedLengthRecordReader搭配使用,詳見tf的CIFAR-10例子

選取與要輸入的文件格式相匹配的reader,并將文件隊列提供給reader的讀方法( read method)。讀方法將返回文件唯一標識的key,以及一個記錄(record)(有助于對出現一些另類的records時debug),以及一個標量的字符串值。再使用一個(或多個)解碼器(decoder) 或轉換操作(conversion ops)將字符串轉換為tensor類型。

#讀取文件隊列,使用reader中read的方法,返回key與value filename_queue = tf.train.string_input_producer(["file0.csv", "file1.csv"]) reader = tf.TextLineReader() key, value = reader.read(filename_queue)record_defaults = [[1], [1], [1], [1], [1]] col1, col2, col3, col4, col5 = tf.decode_csv(value, record_defaults=record_defaults) features = tf.pack([col1, col2, col3, col4])with tf.Session() as sess:# Start populating the filename queue.coord = tf.train.Coordinator()threads = tf.train.start_queue_runners(coord=coord)for i in range(1200):# Retrieve a single instance:example, label = sess.run([features, col5])coord.request_stop()coord.join(threads)

總結

以上是生活随笔為你收集整理的TensorFlow(五)常用函数与基本操作的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。