方法tf.reshape()快速理解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Little_Matches/article/details/81233826

方法:tf.reshape(tensor, shape, name=None)

看个例子:

import tensorflow as tf
#首先我们定义一个二维数组(一共有num = 40 个参数):
arraylist= [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
            [3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
            [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]

input = tf.constant(arraylist)

#reshape里面的参数的乘积必须是等于上面数组所有参数的总和 
#即 x * y * z = num     4 * 2 * 5 = 40
#结果为一个三维数组
output_1 = tf.reshape(input, [4, 2, 5])

#为-1时, 要注意的是reshape里面最多有一个维度的值可以填写为-1,表示自动计算(自动计算出来的值为:4 )。
output_2 = tf.reshape(input, [-1,2, 5])

arrays = []
arrays.append(output_1)
arrays.append(output_2)
#运行
with tf.Session() as sess:
    print('-----output_1    reshape(4, 2, 5):  ----')
    print(output_1)
    print(sess.run(arrays[0]))
    print('-----output_2    reshape(-1, 2, 5):  ----')
    print(output_2)
    print(sess.run(arrays[1]))

运行结果可以知道output_1 = output_2

-----output_1    reshape(4, 2, 5):  ----
Tensor("Reshape:0", shape=(4, 2, 5), dtype=int32)
[[[0 1 2 3 4]
  [5 6 7 8 9]]
 [[1 1 1 1 1]
  [1 1 1 1 1]]
 [[3 3 3 3 3]
  [3 3 3 3 3]]
 [[1 1 1 1 1]
  [1 1 1 1 1]]]
-----output_2    reshape(-1, 2, 5):  ----
Tensor("Reshape_1:0", shape=(4, 2, 5), dtype=int32)
[[[0 1 2 3 4]
  [5 6 7 8 9]]
 [[1 1 1 1 1]
  [1 1 1 1 1]]
 [[3 3 3 3 3]
  [3 3 3 3 3]]
 [[1 1 1 1 1]
  [1 1 1 1 1]]]

猜你喜欢

转载自blog.csdn.net/Little_Matches/article/details/81233826