TensorFlow基本類型及操作函數

TensorFlow 中使用 tensor 來代表所有數據,操作間的數據傳遞也是tensor
tensor 可以看做是一個 n維的數組或列表,
每個tensor都包含 類型(type), 階(rank), 形狀(shape)

1)類型  

tensor類型    Python類型      描述
DT_FLOAT   tf.float32  32位浮點數
DT_DOUBLE   tf.float64  64位浮點數
DT_INT64  tf.int6464位有符號整數
DT_INT32  tf.int32  32位有符號整數
DT_INT16 tf.int1616位有符號整數
DT_INT8tf.int8  8位有符號整數
DT_UNIT8 tf.unit8 8位無符號整數
DT_STRINGtf.string可變長度的字節數組,每個張量都是一個字節數組
DT_BOOLtf.bool 布爾型
DT_COMPLEX64tf.complex64有兩個32位浮點數組成的複數,實數和虛數        

2)階(rank)

指的是維度。張量的階和矩陣的階不是一個概念,主要是看有幾層[],

標量、向量、矩陣的階數

rank實例例子
0標量,只有大小a=1
1向量(大小和方向) b=[]
2矩陣(數據表) c=[[], []]
33階張量(數據立體)d=[[[], []], [[], []]]
nn階 e=[[[[[...]]]]] n層[]                                    

3)shape

shape用於組織張量內部的組織關係。shape可以通過Python中的整數列表或元組來表示

也可以用 TensorFlow 中的相關函數來描述

tensor的相關操作

主要包括:類型轉換、數值操作、形狀變換、數據操作
類型轉換                   
tf.string_to_number(string_tensor, name=None) 字符串轉換爲數字
tf.to_double(x, name=None)   轉換爲64位浮點數
tf.to_float(x, name=None)  轉換爲32位浮點數
tf.to_int32(x, name=None)  轉換爲32位整數
tf.to_int64(x, name=None)   轉換爲64位整數
tf.to_cast(x, dtype, name=None) 將x或x.values 轉換爲dtype所指定的類型
數值操作
函數                                                                      描述
tf.ones(shape, dtype)  指定shape和dtype生成值爲1的張量
tf.ones_like(input)   生成和輸入向量一樣的形狀和類型的1
tf.zeros(shape, dtype)  指定shape和dtype生成值爲1的張量
tf.zeros_like(input)   生成和輸入向量一樣的形狀和類型的1
tf.fill(shape, value) 爲指定形狀填值
tf.constant(value, shape)生成常量
tf.set_random_seed(seed) 設置隨機數種子
tf.random_normal(shape, mean=0., stddev=1.,   dtype=tf.float32, seed=None, name=None)正態隨機分佈 均值mean,標準差stddev

tf.random_uniform(shape, minval=0,  maxval=None, 

dtype=tf.float32, seed=None,name=None)

均勻分佈隨機數 範圍[minval, maxval]

tf.truncated_normal(shape, mean=0., stddev=1.,  

dtype=tf.float32, seed=None,  name=None)                     

截斷正態隨機分佈 均值mean,標準差stddev 只保留[mean-2*stddev, mean+2*stddev]  範圍內的隨機數
tf.random_crop(value, size, seed=None, name=None)       將輸入值value按照size尺寸隨機剪輯
tf.linspace(start, stop, num, name=None)                 在[start,stop]範圍內產生num個數的等差數列
tf.range(start, limit=None, delta=1, name='range')       在[start,limit)範圍內以步進值delta等差數列
形狀變換   
函數  描述
tf.shape(input, name=None) 返回一個張量, 其值爲輸入參數input的shape。input可以是張量,也可以是數組或list
tf.reshape(input, shape, name=None)將原有的輸入數據shape按照指定的形狀進行變換,生成一個新的張量
tf.size(input, name=None)  返回一個張量,其值爲input的元素數量
tf.rank(input, name=None)返回一個張量,其值爲input的rank
tf.expand_dims(input, dim, name=None) 在tensor中插入一個維度  tf.expand_dim(t, num)   num=0,1,2...
tf.squeeze(input, dim, name=None)去除一個維度
數據操作
函數 描述
tf.slice(input_, begin, size, name=None) 對input進行切片操作, begin和size可以爲list類型
tf.split(value, num_or_size_splits,       
         axis=0,num=None,name='split')
沿着某一維度將tensor分離爲num_or_size_splits
tf.concat(values, axis, name="concat") 沿着某一維度連接tensor
tf.stack(values, axis=0, name="stack")  將多個tensor沿着某一軸組合成新的張量
tf.unstack(value, num=None, axis=0, name="unstack") 沿着某一維度拆分 tensor  axis=0 按行, axis=1 按列
tf.gather(params, indices, validate_indices=None, name=None, axis=0)合併索引indices所指示params中的切片
tf.one_hot(indices,depth, on_value=None, off_value=None,   
            axis=None, dtype=None, name=None)
生成符合one_hot編碼的張量
tf.count_nonzero(input_tensor, axis=None,keepdims=None,    
                  dtype=dtypes.int64, name=None,
                  reduction_indices=None,
                  keep_dims=None)
統計非0個數
算術運算函數
函數                                       描述
tf.assign(x, y, name=None)                令 x = y
tf.add(x, y, name=None)                   求和
tf.subtract(x, y, name=None)                 減法
tf.multiply(x, y, name=None)                    乘法
tf.divide(x, y, name=None)                         除法 = tf.div()
tf.mod(x, y, name=None)                               取模
tf.abs(x, name=None)                               求絕對值
tf.negative(x, name=None)                               取負
tf.sign(x, name=None)                               返回x的符號
tf.inv(x, name=None)                                    取反
tf.square(x, name=None)                               
tf.round(x, name=None)                               舍入最接近的整數
tf.sqrt(x, name=None)                               開根號
tf.pow(x, y, name=None)                                  冪運算
tf.exp(x, name=None)                              e的次方
tf.log(x, name=None)                               計算對數
tf.maximum(x, y, name=None)                              返回最大值
tf.minimum(x, name=None)                               返回最小值
tf.cos(x, name=None)                               三角函數 cos
tf.cos(x, name=None)                               三角函數 cos
tf.sin(x, name=None)                               三角函數 sin
tf.tan(x, name=None)                               三角函數 tan

tf.atan(x, name=None)                               

三角函數 ctan


tf.cond(pred, true_fn=None, false_fn=None,    
         strict=False, name=None,
         fn1=None, fn2=None)

 滿足條件就執行 fn1, 否則執行 fn2



矩陣運算 
函數  描述
tf.diag(diagonal, name=None)  返回一個給定對角值的對角tensor
tf.diag_part(input, name=None) 獲得tensor的對角線上的值
tf.trace(x, name=None)  計算一個tensor的跡  即對角線的和
計算一個tensor的跡  即對角線的和計算一個tensor的跡  即對角線的和    按照參數perm指定的維度順序對a進行轉置操作
tf.reverse(tensor, axis, name=None) 沿着指定的維度對輸入進行反轉, axis爲輸入shape的索引列表
tf.matmul(a, b, transpose_a=False, transpose_b=False,
           adjoint_a=False, adjoint_b=False,
           a_is_sparse=False,b_is_sparse=False, name=None)    
矩陣相乘
tf.matrix_determinant(input, name=None) 返回方陣的行列式
tf.matrix_inverse(input, adjoint=False, name=None)  求方陣的逆矩陣, adjoint爲True時,計算輸入共軛矩陣的逆矩陣
tf.cholesky(input, name=None)  對輸入方陣進行cholesky分解,即把一個對稱正定矩陣表示成一個下三角矩陣和其轉置的乘積的分解 A=LL^T
tf.matrix_solve(matrix, rhs, adjoint=False,                                               name=None)  求解矩陣方程,返回矩陣變量  matrix爲矩陣變量的係數, rhs爲矩陣方程的結果
複數操作                     
函數  描述
tf.complex(real, imag, name=None)  將兩個實數轉換爲複數形式
tf.complex_abs(x, name=None) 計算複數的絕對值, 即長度
tf.conj(input, name=None) 計算共軛素數
tf.imag(input, name=None)提取複數的虛部
tf.real(input, name=None)  提取複數的實部
tf.fft(input, name=None) 計算一爲的離散傅里葉變換,輸入數據類型爲 complex64
規約計算
函數  描述
tf.reduce_sum(input_tensor, axis=None, keepdims=None,            
               name=None, reduction_indices=None,
               keep_dims=None)
按照指定軸對input_tensor進行求和
tf.reduce_prod(input_tensor, axis=None, keepdims=None,           
                name=None, reduction_indices=None,
                keep_dims=None)
按照指定軸對input_tensor進行求積
tf.reduce_min(input_tensor, axis=None, keepdims=None,           
               name=None, reduction_indices=None,
               keep_dims=None)
 求input_tensor中的最小值
tf.reduce_max(input_tensor, axis=None, keepdims=None,            
               name=None, reduction_indices=None,
               keep_dims=None)
求input_tensor中的最大值
tf.reduce_mean(input_tensor, axis=None, keepdims=None,           
                name=None, reduction_indices=None,
                keep_dims=None)
求input_tensor中的平均值
tf.reduce_all(input_tensor, axis=None, keepdims=None,           
               name=None, reduction_indices=None,
               keep_dims=None)
 對input_tensor中的各元素求邏輯'與'
tf.reduce_any(input_tensor, axis=None, keepdims=None,          
               name=None, reduction_indices=None,
               keep_dims=None)
  對input_tensor中的各元素求邏輯'或'
分割                  
函數 描述
tf.segment_sum(data, segment_ids, name=None)   沿着segment_ids指定的維度,分割張量data中的值,並且返回累加值
tf.segment_prod(data, segment_ids, name=None)  根據segment_ids的分段計算各個片段的積
tf.segment_min(data, segment_ids, name=None)根據segment_ids的分段計算各個片段的最小值
tf.segment_max(data, segment_ids, name=None)  根據segment_ids的分段計算各個片段的最大值
tf.segment_mean(data, segment_ids, name=None) 根據segment_ids的分段計算各個片段的平均值
tf.unsorted_segment_sum(data, segment_ids, num_segment, name=None) 與tf.segment_sum類似,但是tf.segment_sum可以無序
tf.sparse_segment_sum(data, indices, segment_ids, name=None) 對data進行稀疏分割求和
序列比較於索引提取                              
函數  描述
tf.argmin(input, axis, name=None)根據給出的axis,返回input中最小值的索引
tf.argmax(input, axis, name=None) 根據給出的axis,返回input中最大值的索引
tf.setdiffld(x, y, name=None) 返回x,y中不同值得索引
tf.where(condition, c=None, y=None, name=None)

根據指定的條件,返回對應的值或座標,若x,y都爲None

返回condition值爲True的座標,若都不爲None,
返回值爲True的座標在x內的值,condition值爲False的座標在y內的值

tf.unique(x, name=None)返回一個tuple(y,idx), y爲x列表的唯一化數據列表,idx爲x數據對應y元素的index
tf.invert_permutation(x, name=None) 計算序列的逆置換(inverse permutation)
本操作是計算張量的索引的逆置換。
x是一維的整數張量,表示一個以0爲開始的索引數組,然後根據這裏元素的值來放入整數,
計算公式如下:
                        y[x[i]] = i for i in [0, 1, ..., len(x) -1]
tf.random_shuffle(input)   沿着input的第一維進行隨機重新排列
錯誤類          
函數 描述
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.NotFountError找不到請求的實體時報錯,例如文件、目錄
class tf.errors.AlreadyExistsError 當創建的實體已經存在時報錯
class tf.errors.PermissionDeniedError 沒有執行權限
class tf.errors.ResourceExhaustError  資源耗盡報錯
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.errors.XXXXX.__init__(node_def, op, message) 使用該方式創建以上各種錯誤類
下面是在網上看到的一個問題及解決方法:
tf.unsorted_segment_sum(tf.constant([0.2, 0.1, 0.5, 0.7, 0.8]),
                        tf.constant([0, 0, 1, 2, 2]), 3)
上面輸出結果爲:   array([ 0.3,  0.5 , 1.5 ], dtype=float32)
tf.unsorted_segment_sum(tf.constant([[0.2, 0.1, 0.5, 0.7, 0.8],
                                     [0.2, 0.2, 0.5, 0.7, 0.8]]),
                        tf.constant([[0, 0, 1, 2, 2],
                                     [0, 0, 1, 2, 2]]), 3)
上面這個的輸出爲:  array([ 0.7,  1. ,  3. ], dtype=float32)
如果想要輸出下面的結果,應該怎麼辦呢?
array([ [ 0.3,  0.5 , 1.5 ], [ 0.4, 0.5, 1.5 ] ], dtype=float32)
第一: 通過轉置
import tensorflow as tf
with tf.Session() as sess:
    data = tf.constant([[0.2, 0.1, 0.5, 0.7, 0.8],
                        [0.2, 0.2, 0.5, 0.7, 0.8]])
    idx = tf.constant([0, 0, 1, 2, 2])
    result = tf.transpose(tf.unsorted_segment_sum(tf.transpose(data), idx, 3))
    print(sess.run(result))
Output:
[[ 0.30000001  0.5         1.5       ]
 [ 0.40000001  0.5         1.5       ]]
第二:
data = tf.constant([[0.2, 0.1, 0.5, 0.7, 0.8],
                    [0.2, 0.2, 0.5, 0.7, 0.8]])
segment_ids = tf.constant([[0, 0, 1, 2, 2],
                           [0, 0, 1, 2, 2]])
num_segments = 3
rows = []
for data_i, ids_i in zip(data, segment_ids):
    rows.append(tf.unsorted_segment_sum(data_i, ids_i))
result = tf.stack(rows, axis=0)
第三:
num_rows = tf.shape(segment_ids)[0]
rows_idx = tf.range(num_rows)
segment_ids_per_row = segment_ids + num_segments * tf.expand_dims(rows_idx, axis=1)
seg_sums = tf.unsorted_segment_sum(data, segment_ids_per_row,
                                   num_segments * num_rows)
result = tf.reshape(seg_sums, [-1, num_segments])
Output:
array([[ 0.3, 0.5, 1.5 ],
       [ 0.4, 0.5, 1.5 ]], dtype=float32)

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