记录 之 tensorflow中几个常用的函数:tf.unstack,tf.concat() 和 tf.stack() 等
1.tf.to_int32();tf.to_float()等 函數,主要是強制類型轉換函數;
2.tf.shape(tensor);獲取tensor的尺寸
3.tf.round(a);四舍五入函數,張量的值四舍五入為最接近的整數
4.tf.unstack(matrix, axis? =? ‘ ’?);矩陣分解函數
 matrix:需要拆解的矩陣
 axis:沿某一維度進行拆解,值得注意的是,在使用的時候,axis = 不可缺省,axis 取值范圍是[-a,a),a是matrx的維度
例:
import tensorflow as tfmat = tf.constant([1,2,3],[4,5,6])o1 = tf.unstack(mat,axis = 0)o2 = tf.unstack(mat,axis = 1)sess = tf.Session()print(sess.run(o1))>>>[array([1, 2, 3]), array([3, 4, 5])]>>>[array([1, 3]), array([2, 4]), array([3, 5])]5.tf.concat() 和 tf.stack() 是我們需要重點區分的兩個函數,兩者講道理功能都是進行張量拼接,但是tf.concat函數不會在原有的基礎上增加維度,所以在進行通道拼接時常選用tf.concat。而tf.stack()函數在原有的基礎上增加一個維度,即由原來的n維變換為n+1維,我們分別來看兩個例子:
(1). tf.concat()
import tensorflow as tfa = tf.constant([[[1,2],[2,3],[3,4]], [[5,6],[7,8],[8,9]]]) #[1,3,2] b = tf.constant([[[11,12],[12,13],[13,14]], [[15,16],[17,18],[18,19]]]) #[1,3,2]o1 = tf.concat([a,b], axis = 0)o2 = tf.concat([a,b], axis = 1)o3 = tf.concat([a,b], axis = 2)sess = tf.Session()print(sess.run(o1))print(sess.run(o2))print(sess.run(o3))output:>>>[[[ 1 2][ 2 3][ 3 4]][[ 5 6][ 7 8][ 8 9]][[11 12][12 13][13 14]][[15 16][17 18][18 19]]] #維度:[2,3,2] >>>[[[ 1 2][ 2 3][ 3 4][11 12][12 13][13 14]][[ 5 6][ 7 8][ 8 9][15 16][17 18][18 19]]] #維度:[1,6,2] >>>[[[ 1 2 11 12][ 2 3 12 13][ 3 4 13 14]][[ 5 6 15 16][ 7 8 17 18][ 8 9 18 19]]] #維度:[1,3,4](2).tf.stack()
import tensorflow as tfa = tf.constant([[1,2],[2,3],[3,4]]) #[3,2] b = tf.constant([[5,6],[7,8],[8,9]]) #[3,2]o1 = tf.stack([a,b], axis = 0)o2 = tf.stack([a,b], axis = 1)o3 = tf.stack([a,b], axis = 2)sess = tf.Session()print(sess.run(o1))print(sess.run(o2))print(sess.run(o3))output: >>>[[[1 2][2 3][3 4]][[5 6][7 8][8 9]]] #維度:[2,3,2]>>>[[[1 2][5 6]][[2 3][7 8]][[3 4][8 9]]] #維度:[3,2,2]>>>[[[1 5][2 6]][[2 7][3 8]][[3 8][4 9]]] #維度:[3,2,2]這個變換過程手動操作可以理解,以axis = 1 為例:
先將a變換為維度為[3,1,2]的矩陣:即
[[[1,2]],[[2,3]],[[3,4]]]?同理b做同樣的變換,即
[[[5,6]],[[6,7]],[[7,8]]]然后就做類似concat的操作,即成為了:
[[[1 2][5 6]][[2 3][7 8]][[3 4][8 9]]]到這里我們就知道了tf.caoncat 和 tf.stack的區別及作用,也學會了手動操作。
 ?
?
?
總結
以上是生活随笔為你收集整理的记录 之 tensorflow中几个常用的函数:tf.unstack,tf.concat() 和 tf.stack() 等的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: mindspore学习之使用obsuti
 - 下一篇: 记录 之 tensorflow 常用函