先来看一下tf.reshape()函数的语法结构:
tf.reshape(tensor, shape, name=None)
其中,tensor可以理解为变量;shape就是数据格式;name默认为None。
这个函数的作用是将tensor变换为参数shape的形式。
与常用的更改结构的函数的最大不同在于tf.reshape()函数中经常会用到-1,那么这个-1是什么作用呢?
先来看一下官方解释
意思就是,哪一维使用了-1,那这一维度就不定义大小,而是根据你的数据情况进行匹配。即先不管-1的那一个维度,先看其他维度,然后用原矩阵的总元素个数除以确定的维度,就能得到-1维度的值。
不过要注意:但列表中只能存在一个-1。
下面用代码进行演示:
import numpy as np
z = np.array([[1, 2, 3, 4],
...: [5, 6, 7, 8],
...: [9, 10, 11, 12],
...: [13, 14, 15, 16]])
...:
z.reshape(-1)
Out[12]: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
z.reshape(2,-1)
Out[13]:
array([[ 1, 2, 3, 4, 5, 6, 7, 8],
[ 9, 10, 11, 12, 13, 14, 15, 16]])
z.reshape(-1,2)
Out[14]:
array([[ 1, 2],
[ 3, 4],
[ 5, 6],
[ 7, 8],
[ 9, 10],
[11, 12],
这里演示的时候使用的是正常的reshape()函数,跟tf.reshape()原理是一样的。