深度學習中張量flatten處理(flatten,reshape,reduce)
阿新 • • 發佈:2018-11-07
先看一下flatten的具體用法
1-對於一般數值,可以直接flatten
>>> a=array([[1,2],[3,4],[5,6]])
>>> a
array([[1, 2],
[3, 4],
[5, 6]])
>>> a.flatten()
array([1, 2, 3, 4, 5, 6])
2-對列表變數,需要做一下處理
>>> a=array([[1,2],[3,4],[5,6]]) >>> [y for x in a for y in x] [1, 2, 3, 4, 5, 6]
3-對mat物件
>>> a = [[1,3],[2,4],[3,5]] >>> a = mat(a) >>> y = a.flatten() >>> y matrix([[1, 3, 2, 4, 3, 5]]) >>> y = a.flatten().A >>> y array([[1, 3, 2, 4, 3, 5]]) >>> shape(y) (1, 6) >>> shape(y[0]) (6,) >>> y = a.flatten().A[0] >>> y array([1, 3, 2, 4, 3, 5])
4-壓縮(reduce)
slopes=tf.sqrt(tf.reduce_sum(tf.square(gradients),reduction_indices=[1])
其中reduction_indices=1表示按行壓縮,=0表示按列壓縮
5-reshape
tf.reshape(tensor,shape,name=None)
tensor是我們輸入的張量,shape是我們希望輸入變成什麼形狀,其中的shape為一個列表形式,特殊的是列表可以實現逆序的遍歷,即list(-1).-1所代表的含義是我們不用親自去指定這一維的大小,函式會自動進行計算,但是列表中只能存在一個-1。如一個6元素的陣列,想要reshape成2*3時,下面三種寫法得到的結果都是一樣的
tf.reshape(a,[2,3])
tf.reshape(a,[2,-1])
tf.reshape(a,[-1,3])