Tensorflow.org 個人日常函數(shù)

記錄本人在使用 tensorflow 過程中遇到過的函數(shù),長期更新。

1. def reshape(tensor, shape, name=None)

第1個參數(shù)為被調(diào)整維度的張量。
第2個參數(shù)為要調(diào)整為的形狀。
返回一個shape形狀的新tensor
注意shape里最多有一個維度的值可以填寫為-1,表示自動計算此維度。shape是一個列表形式
好了我想說的重點(diǎn)還有一個就是根據(jù)shape如何變換矩陣。其實簡單的想就是,

reshape(t, shape) => reshape(t, [-1]) => reshape(t, shape)

首先將矩陣t變?yōu)橐痪S矩陣,然后再對矩陣的形式更改就可以了。

關(guān)于shape
# tensor 't' is [1, 2, 3, 4, 5, 6, 7, 8, 9]
# tensor 't' has shape [9]

# tensor 't' is [[[1, 1], [2, 2]],
#                [[3, 3], [4, 4]]]
# tensor 't' has shape [2, 2, 2]

# tensor 't' is [[[1, 1, 1],
#                 [2, 2, 2]],
#                [[3, 3, 3],
#                 [4, 4, 4]],
#                [[5, 5, 5],
#                 [6, 6, 6]]]
# tensor 't' has shape [3, 2, 3]

2. tf.concat(concat_dim, values, name='concat')

concat_dim:必須是一個數(shù),表明在哪一維上連接

如果concat_dim是0 可以理解為使行變大
t1 = [[1, 2, 3], [4, 5, 6]]
t2 = [[7, 8, 9], [10, 11, 12]]
tf.concat(0, [t1, t2]) == > [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

如果concat_dim是1 可以理解為使列變大
t1 = [[1, 2, 3], [4, 5, 6]]
t2 = [[7, 8, 9], [10, 11, 12]]
tf.concat(1, [t1, t2]) ==> [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12

如果有更高維:

# tensor t3 with shape [2, 3]  
# tensor t4 with shape [2, 3]  
tf.shape(tf.concat(0, [t3, t4])) ==> [4, 3]  
tf.shape(tf.concat(1, [t3, t4])) ==> [2, 6] 

3. tf.add_to_collection(self, name, value)

將value以name的名稱存儲在收集器(self._collections)中.

import tensorflow as tf
v1 = tf.get_variable('v1', shape=[1], initializer=tf.ones_initializer())
v2 = tf.get_variable('v2', shape=[1], initializer=tf.zeros_initializer())
tf.add_to_collection('vc', v1)
tf.add_to_collection('vc', v2)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    vc = tf.get_collection('vc')
    print(vc)
    for i in vc:
        print(i)
        print(sess.run(i))
輸出
[<tf.Variable 'v1:0' shape=(1,) dtype=float32_ref>, <tf.Variable 'v2:0' shape=(1,) dtype=float32_ref>]
<tf.Variable 'v1:0' shape=(1,) dtype=float32_ref>
[ 1.]
<tf.Variable 'v2:0' shape=(1,) dtype=float32_ref>
[ 0.]

4. tf.ones_like(tensor,dype=None,name=None)

新建一個與給定的tensor類型大小一致的tensor,其所有元素為1。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容