Tensorflow中reshape()函数的使用

初学tensorflow,如果不对请指正,谢谢
tenorflow中有一个函数叫reshape()函数,这个函数可以将输入的tensor变换成shape的格式。具体看函数说明:

def reshape(tensor, shape, name=None):
  Reshapes a tensor.

  Given `tensor`, this operation returns a tensor that has the same values
  as `tensor` with shape `shape`.

  If one component of `shape` is the special value -1, the size of that dimension
  is computed so that the total size remains constant.  In particular, a `shape`
  of `[-1]` flattens into 1-D.  At most one component of `shape` can be -1.

  If `shape` is 1-D or higher, then the operation returns a tensor with shape
  `shape` filled with the values of `tensor`. In this case, the number of elements
  implied by `shape` must be the same as the number of elements in `tensor`.

1.给定一个tensor,怎么确定它的shape。
2.给定一个tensor和shape,经过reshape(tensor,shape)变换后返回的tensor是什么格式的。
先看一看文档中给出的例子:

For example:

  ```prettyprint
  # tensor 't' is [1, 2, 3, 4, 5, 6, 7, 8, 9]
  # tensor 't' has shape [9]
  reshape(t, [3, 3]) ==> [[1, 2, 3],
                          [4, 5, 6],
                          [7, 8, 9]]

  # tensor 't' is [[[1, 1], [2, 2]],
  #                [[3, 3], [4, 4]]]
  # tensor 't' has shape [2, 2, 2]
  reshape(t, [2, 4]) ==> [[1, 1, 2, 2],
                          [3, 3, 4, 4]]

  # tensor 't' is [[[1, 1, 1],
  #                 [2, 2, 2]],
  #                [[3, 3, 3],
  #                 [4, 4, 4]],
  #                [[5, 5, 5],
  #                 [6, 6, 6]]]
  # tensor 't' has shape [3, 2, 3]

首先,tensor的维数与shape中元素的个数是相等的;其次,shape中数字的乘积与tensor中元素的个数相等,因此在调用reshape()函数时应注意元素个数保持一致。要确定给定的tensor的shape,应该从外往里看。例如

  # tensor 't' is [[[1, 1], [2, 2]],
  #                [[3, 3], [4, 4]]]
  # tensor 't' has shape [2, 2, 2]
  reshape(t, [2, 4]) ==> [[1, 1, 2, 2],
                          [3, 3, 4, 4]]

经过reshape变化的t,最外层包含两个元素,里面一层包含4个元素,相当于2维数组。变化之前的t,最外层包含两个元素(第一行末尾一个逗号隔开),中间层每层两个元素(第一行中间一个逗号隔开),最内层两个元素,相当于三维数组。
给定了tensor和shape后,将tensor按一维展开,再按照给定的shape重新组合。
如果shape中有-1,函数会自动计算维度,但只能有有个-1.

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值