歡迎您光臨本站 註冊首頁

有一段時間沒用tensorflow了,現在跑實驗還是存在一些坑了,主要是關於張量計算的問題。tensorflow升級1.0版本後與以前的版本並不相容,可能出現各種奇奇怪怪的問題。

1 tf.concat函式

tensorflow1.0以前函式用法:tf.concat(concat_dim, values, name='concat'),第一個引數為連線的維度,可以將幾個向量按指定維度連線起來。

如:

  t1 = [[1, 2, 3], [4, 5, 6]]  t2 = [[7, 8, 9], [10, 11, 12]]  #按照第0維連線  tf.concat(0, [t1, t2]) ==> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]  #按照第1維連線  tf.concat(1, [t1, t2]) ==> [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]]

 

tf.concat的作用主要是將向量按指定維連起來,其餘維度不變;而1.0版本以後,函式的用法變成:

  t1 = [[1, 2, 3], [4, 5, 6]]  t2 = [[7, 8, 9], [10, 11, 12]]  #按照第0維連線  tf.concat( [t1, t2],0) ==> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]  #按照第1維連線  tf.concat([t1, t2],1) ==> [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]]

 

位置變了,需要注意。

2 tf.stack函式

用法:stack(values, axis=0, name=」stack」):

「」「Stacks a list of rank-R tensors into one rank-(R+1) tensor.

  x = tf.constant([1, 4])  y = tf.constant([2, 5])  z = tf.constant([3, 6])  tf.stack([x,y,z]) ==> [[1,4],[2,5],[3,6]]  tf.stack([x,y,z],axis=0) ==> [[1,4],[2,5],[3,6]]  tf.stack([x,y,z],axis=1) ==> [[1, 2, 3], [4, 5, 6]]

 

tf.stack將一組R維張量變為R+1維張量。注意:tf.pack已經變成了tf.stack

3.tf.reshape

用法:reshape(tensor, shape, name=None):主要通過改變張量形狀,可以從高維變低維,也可以從低維變高維;

  a = tf.Variable(initial_value=[[1,2,3],[4,5,6]]) ==> shape:[2,3]  b = tf.Variable(initial_value=[[[1,2,3],[4,5,6]],[[7,8,9],[1,0,2]]]) ==> shape:[2,2,3]    a_1 = tf.reshape(a,[2,1,1,3]) ==> [[[[1,2,3]]],[[[4,5,6]]]]  a_2 = tf.reshape(a,[2,1,3]) ==> [[[1,2,3]],[[4,5,6]]]  b_1 = tf.reshape(b,[2,2,1,3]) ==> [[[[1,2,3]],[[4,5,6]]],[[[7,8,9]],[[1,0,2]]]]    new_1 = tf.concat([b_1,a_1],1)  new_2 = tf.reshape(tf.concat([b,a_2],1),[2,3,1,3])  """  new_1:  [[[[1 2 3]]     [[4 5 6]]     [[1 2 3]]]       [[[7 8 9]]     [[1 0 2]]     [[4 5 6]]]]  new_2;  [[[[1 2 3]]     [[4 5 6]]     [[1 2 3]]]       [[[7 8 9]]     [[1 0 2]]     [[4 5 6]]]]

 

補充知識:tensorflow中的reshape(tensor,[1,-1])和reshape(tensor,[-1,1])

和python 中的reshape用法應該一樣

  import tensorflow as tf  a = [[1,2],[3,4],[5,6]]  tf.reshape(a,[-1,1])  Out[13]:tf.reshape(tf.reshape(a,[-1,1]),[1,-1])  Out[14]:

 

tf.reshape(tensor,[-1,1])將張量變為一維列向量

tf.reshape(tensor,[1,-1])將張量變為一維行向量

 


[sl_ivan ] 淺談tensorflow使用張量時的一些注意點tf.concat,tf.reshape,tf.stack已經有403次圍觀

http://coctec.com/docs/program/show-post-239530.html