import tensorflow as tf rank_three_tensor = tf.ones([3, 4, 5]) # 創建一個[3,4,5]大小的張量,3行4列,每個位置上有五個元素 matrix = tf.reshape(rank_three_tensor, [6, 10]) # 將當前變量reshape成[6,10]個大小的變量 matrixB = tf.reshape(matrix, [3, -1]) # 將現有內容改造成3×20矩陣。-1指定這個維度的元素個數根據其他維度的元素個數來計算。 matrixAlt = tf.reshape(matrixB, [4, 3, -1]) # 將當前的矩陣reshape成 4行3列每個位置上為5個元素的 tensor # 改變張量的形狀 # The number of elements of a scalar is always # 1、因為經常有許多不同的形狀具有相同數量的元素。 # 所以改變這樣的張量的形狀,使得reshape前后的張量中元素的數量是相同的, init = tf.global_variables_initializer() sess = tf.Session() print(sess.run(rank_three_tensor)) print(sess.run(matrix)) print(sess.run(matrixB)) print(sess.run(matrixAlt))
下邊是上面代碼輸出的結果
2018-02-16 20:33:55.488664: I C:\tf_jenkins\workspace\rel-win\M\windows\PY\35\tensorflow\core\platform\cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2 [[[ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.]] [[ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.]] [[ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.]]] [[ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]] [[ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]] [[[ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.]] [[ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.]] [[ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.]] [[ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.]]]