Tensorflow - tf常用函數使用(持續更新中)


本人較懶,故間斷更新下常用的tf函數以供參考: 

 

一、tf.reduce_sum( )

reduce_sum( ) 個人理解是降維求和函數,在 tensorflow 里面,計算的都是 tensor,可以通過調整 axis 的維度來控制求和維度。

參數:

  • input_tensor:要減少的張量.應該有數字類型.
  • axis:要減小的尺寸.如果為None(默認),則縮小所有尺寸.必須在范圍[-rank(input_tensor), rank(input_tensor))內.
  • keep_dims:如果為true,則保留長度為1的縮小尺寸.
  • name:操作的名稱(可選).
  • reduction_indices:axis的廢棄的名稱.

返回:

該函數返回減少的張量.

numpy兼容性

相當於np.sum;

 

此處axis為tensor的階數,使用該函數將消除tensor指定的階axis,同時將該階下的所有的元素進行累積求和操作。

看一個官方示例:

x = tf.constant([[1, 1, 1], [1, 1, 1]])
tf.reduce_sum(x)  # 6
tf.reduce_sum(x, 0)  # [2, 2, 2]
tf.reduce_sum(x, 1)  # [3, 3]
tf.reduce_sum(x, 1, keep_dims=True)  # [[3], [3]]
tf.reduce_sum(x, [0, 1])  # 6

此函數計算一個張量的各個維度上元素的總和. 

函數中的input_tensor是按照axis中已經給定的維度來減少的;除非 keep_dims 是true,否則張量的秩將在axis的每個條目中減少1;如果keep_dims為true,則減小的維度將保留為長度1. 

如果axis沒有條目,則縮小所有維度,並返回具有單個元素的張量.

 

 二、tf.ones_like | tf.zeros_like

tf.ones_like(tensor,dype=None,name=None)
tf.zeros_like(tensor,dype=None,name=None)
新建一個與給定的tensor類型大小一致的tensor,其所有元素為1和0,示例如下:

tensor=[[1, 2, 3], [4, 5, 6]] 
x = tf.ones_like(tensor) 
print(sess.run(x))

#[[1 1 1],
# [1 1 1]]

 

三、tf.reduce_mean()

tf.reduce_mean 函數用於計算張量tensor沿着指定的數軸(tensor的某一維度)上的的平均值,主要用作降維或者計算tensor(圖像)的平均值。

reduce_mean(input_tensor,
                axis=None,
                keep_dims=False,
                name=None,
                reduction_indices=None)

第一個參數input_tensor: 輸入的待降維的tensor;
第二個參數axis: 指定的軸,如果不指定,則計算所有元素的均值;
第三個參數keep_dims:是否降維度,設置為True,輸出的結果保持輸入tensor的形狀,設置為False,輸出結果會降低維度;
第四個參數name: 操作的名稱;
第五個參數 reduction_indices:在以前版本中用來指定軸,已棄用;

以一個維度是2,形狀是[2,3]的tensor舉例:

import tensorflow as tf
 
x = [[1,2,3],
      [1,2,3]]
 
xx = tf.cast(x,tf.float32)
 
mean_all = tf.reduce_mean(xx, keep_dims=False)
mean_0 = tf.reduce_mean(xx, axis=0, keep_dims=False)
mean_1 = tf.reduce_mean(xx, axis=1, keep_dims=False)
 
 
with tf.Session() as sess:
    m_a,m_0,m_1 = sess.run([mean_all, mean_0, mean_1])
 
print m_a    # output: 2.0
print m_0    # output: [ 1.  2.  3.]
print m_1    #output:  [ 2.  2.]

如果設置保持原來的張量的維度,keep_dims=True ,結果:

print m_a    # output: [[ 2.]]
print m_0    # output: [[ 1.  2.  3.]]
print m_1    #output:  [[ 2.], [ 2.]]
 
 

 

類似的函數還有:

  • tf.reduce_sum :計算tensor指定軸方向上的所有元素的累加和;
  • tf.reduce_max  :  計算tensor指定軸方向上的各個元素的最大值;
  • tf.reduce_all :  計算tensor指定軸方向上的各個元素的邏輯和(and運算);
  • tf.reduce_any:  計算tensor指定軸方向上的各個元素的邏輯或(or運算);

 

四、tf.concat與tf.stack/unstack( )

tf.concat相當於numpy中的np.concatenate函數,用於將兩個張量在某一個維度(axis)合並起來,例如:

a = tf.constant([[1,2,3],[3,4,5]]) # shape (2,3)
b = tf.constant([[7,8,9],[10,11,12]]) # shape (2,3)
ab1 = tf.concat([a,b], axis=0) # shape(4,3)
ab2 = tf.concat([a,b], axis=1) # shape(2,6)

 

 

tf.stack其作用類似於tf.concat,都是拼接兩個張量,而不同之處在於,tf.concat拼接的是兩個shape完全相同的張量,並且產生的張量的階數不會發生變化,而tf.stack則會在新的張量階上拼接,產生的張量的階數將會增加,增加的那一維的數量為拼接的張量的個數,如兩個張量stack就為2,例如:

a = tf.constant([[1,2,3],[3,4,5]]) # shape (2,3)
b = tf.constant([[7,8,9],[10,11,12]]) # shape (2,3)
ab = tf.stack([a,b], axis=0) # shape (2,2,3)

 

 

 

改變參數axis為2,有:

import tensorflow as tf
a = tf.constant([[1,2,3],[3,4,5]]) # shape (2,3)
b = tf.constant([[7,8,9],[10,11,12]]) # shape (2,3)
ab = tf.stack([a,b], axis=2) # shape (2,3,2)
 

 

 

所以axis是決定其層疊(stack)張量的維度方向的。

tf.unstacktf.stack的操作相反,是將一個高階數的張量在某個axis上分解為低階數的張量,例如:

a = tf.constant([[1,2,3],[3,4,5]]) # shape (2,3)
b = tf.constant([[7,8,9],[10,11,12]]) # shape (2,3)
ab = tf.stack([a,b], axis=0) # shape (2,2,3)

a1 = tf.unstack(ab, axis=0)

 

 

其a1的輸出為

[<tf.Tensor 'unstack_1:0' shape=(2, 3) dtype=int32>,
 <tf.Tensor 'unstack_1:1' shape=(2, 3) dtype=int32>]

 

四、tf.reshape()

tf.reshape(tensor,shape,name=None)

函數的作用是將tensor變換為參數shape形式,其中的shape為一個列表形式,特殊的是列表可以實現逆序的遍歷,即list(-1).-1所代表的含義是我們不用親自去指定這一維的大小,函數會自動進行計算,但是列表中只能存在一個-1。(如果存在多個-1,就是一個存在多解的方程) 

下面就說一下reshape是如何進行矩陣的變換的,其簡單的流程就是: 
將矩陣t變換為一維矩陣,然后再對矩陣的形式進行更改就好了。

接下來是具體的例子,創建一個一維的數組:

>>>import numpy as np
>>>a= np.array([1,2,3,4,5,6,7,8])
>>>a
array([1,2,3,4,5,6,7,8])
>>>

使用reshape()方法來更改數組的形狀,使得數組成為一個二維的數組:(數組中元素的個數是2×4=8)

>>>d = a.reshape((2,4))
>>>d
array([[1, 2, 3, 4],
       [5, 6, 7, 8]])

進一步提升,可以得到一個三維的數組f:(注意數組中元素的個數時2×2×2=8)

>>>f = a.reshape((2,2,2))
>>>f
array([[[1, 2],
        [3, 4]],

       [[5, 6],
        [7, 8]]])

注意:形狀發生變化的原則時數組元素的個數是不能發生改變的,比如像下面這樣的寫法就會報錯: 
(元素的個數是2×2=4,所以會報錯)

>>> e = a.shape((2,2))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

-1 的應用:-1 表示不知道該填什么數字合適的情況下,可以選擇,由python通過a和其他的值3推測出來,比如,這里的a 是二維的數組,數組中共有6個元素,當使用reshape()時,6/3=2,所以形成的是3行2列的二維數組,可以看出,利用reshape進行數組形狀的轉換時,一定要滿足(x,y)中x×y=數組的個數。

>>>a = np.array([[1,2,3],[4,5,6]])
>>>np.reshape(a,(3,-1)) 
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> np.reshape(a,(1,-1))
array([[1, 2, 3, 4, 5, 6]])
>>> np.reshape(a,(6,-1))
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6]])
>>> np.reshape(a,(-1,1))
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6]])

 


免責聲明!

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



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