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: f_jenkinsworkspace el-winMwindowsPY35 ensorflowcoreplatformcpu_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.]]]