天天看點

TensorFlow常用總結

文章目錄

        • 1.計算圖節點與Tensor
        • 2.tf.py_func使用
      • 資料采樣相關函數
        • tf.unique_with_count
        • tf.nn.topk

1.計算圖節點與Tensor

TensorFlow計算圖中每一個節點都定義了一個計算,而計算的結果都通過Tensor 來儲存,是以Tensor和計算圖中節點對應的計算結果所對應,同時Tensor具有3個重要屬性,name,dtype,shape,通過name可以唯一确定計算圖上的一個Tensor,而Tensor通過dtype和shape相當于确定了一個schema,隻有在計算圖每次運作的時候,會有符合該schema的值被賦予到Tensor上。

2.tf.py_func使用

因為在tensorflow中 tensor隻是占位符,隻有在運作的時候才能夠有真是的值填充,這也就導緻了在建構Graph的時候有很多局限,比如 你無法在建構Graph的時候針對某一個operation的運算結果進行if else條件判斷,同時你也無法将某個Operation計算結果直接當做numpy的array進行處理,為了彌補這一局限性 tensorflow中使用tf.py_func進行補充。

tf.py_func函數解析:

tf.py_func(func,inp,Tout,stateful=True,name)
           

定義一個python函數 func,該函數的輸入參數為numpy array形式,輸出也是一個numpy array,tf.py_func将該函數包裝成為一個operation,嵌入到Graph中

func:使用者自定義的python函數,輸入為numpy array,輸出也為numpy array

inp:func函數接收的輸入 是一個Tensor的list

Tout:指定了func函數傳回值轉化為Tensor的資料類型

以一個真實場景舉例

def np_random_choice_sample(self, sample_prob, candidate_num, choice_number):
        two_axis_tensor = tf.constant([[j+i*candidate_num for j in range(candidate_num)] for i in range(self.batch_size)], tf.int32)
        line_num, _ = two_axis_tensor.get_shape()
        result = []
        for i in range(self.batch_size):
            result.append(tf.py_func(np.random.choice, [two_axis_tensor[i], tf.constant(choice_number, tf.int32), tf.constant(False, tf.bool), sample_prob[i]], tf.int32))
        return tf.reshape(tf.concat(result, axis=0), [-1])
           

首先聲明一個Tensor two_axis_tensor ,然後利用 np.random.choice ,因為 np.random.choice 接收4個傳入的參數,要注意在這裡傳入的參數均需要是tf.Variable類型,以list的形式傳入,當傳入參數隻有一個的時候 也需要以list的形式傳入)同時 Tout指定輸出的結果的資料類型,當然如果傳回多個值并且每個值的資料類型不同 可以使用list分别指定不同的資料類型

當然func可以是使用者自定義的任意numpy資料處理集合 但是要注意不可以在func中進行需要反向傳播的操作

資料采樣相關函數

tf.unique_with_count

對于一個1D的數組 其中有若幹重複的元素 想要觀察其中非重複的部分的分布情況,可以使用 tf.unique_with_count

# tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8]
y, idx, count = tf.unique_with_counts(x)
y ==> [1, 2, 4, 7, 8]
idx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4]
count ==> [2, 1, 3, 1, 2]
           

tf.nn.topk

給定Tensor以及k值 ,對于給定的tensor 如果是多元Tensor 則每次采樣都是在最後一維中進行

import numpy as np
a = tf.convert_to_tensor(np.random.random([3,3]))

# 按照最後一個次元取出前5個最大的資料,預設從大到小進行排序。
b = tf.nn.top_k(a, 2)

with tf.Session() as sess:
    print(sess.run(a))
    print(sess.run(b))

[[0.24674883 0.10466478 0.15669153]
 [0.17753881 0.4964197  0.23149027]
 [0.85461829 0.77626046 0.81463996]]
TopKV2(values=array([[0.24674883, 0.15669153],
       [0.4964197 , 0.23149027],
       [0.85461829, 0.81463996]]), indices=array([[0, 2],
       [1, 2],
       [0, 2]], dtype=int32))
           

繼續閱讀