【numpy、pytorch】 .reshape()的元素变动过程(pytorch的view也是此过程)

8 篇文章 2 订阅
8 篇文章 0 订阅

来自: https://zhuanlan.zhihu.com/p/72128096

1、先通过二维数据理解

它的含义说的最清楚的一段话:

You can think of reshaping as first raveling the array (using the given index order), then inserting the elements from the raveled array into the new array using the same kind of index ordering as was used for the raveling. 

翻译过来就是先打散,再按照这个顺序插入;

C 是按照行顺序, F 是按照列顺序,A 就是按照数据在内存中存储的顺序来。

a = array([[0, 1],
           [2, 3],
           [4, 5]])

np.reshape(a, (2, 3), order='F')

>>>Out[9]: 
array([[0, 4, 3],
       [2, 1, 5]])

按照 F 顺序打散后就是 0 2 4 1 3 5, 再按照 F顺序插入, 就是上述的结果。

2、多维数据时

但是有个地方在多维数据的时候容易混淆,就是当我们按照 C 是按照行顺序, F 是按照列顺序去理解多维度数据的时候,这样的解释就不够了(即多维数据不止行和列两个维度)更一般的理解,应该是 C 顺序准确的含义是从最里面的轴开始读写,而F顺序则是从最外面的轴开始读写; 

'C' means to read / write the elements using C-like index order, with the last axis index changing fastest, back to the first axis index changing slowest. 'F' means to read / write the elements using Fortran-like index order, with the first index changing fastest, and the last index changing slowest. 

什么意思呢? 以上面的二维数据 a(3,2) 举例就是,C顺序就是先读写最里面 2 这个轴的数据,也就是得到 0 ,1 ,2,3,4,5 这样的顺序,而F顺序则是从最外层 3 这个轴的数据开始读写,得到 0 2 4 1 3 5 ,多维数据以此类推。

3、补充:numpy和pytorch内的.reshape()函数

numpy里面C是默认值:

pytorch里面,没有order这个选项:

 我验证过了,torch.reshape()也是C:

import torch
import numpy as np

a = np.array([[0, 1],
              [2, 3],
              [4, 5]])

a = torch.from_numpy(a)
b = torch.reshape(a, (2, 3))
print(b)


>>>返回:
tensor([[0, 1, 2],
        [3, 4, 5]])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值