python numpy高维数组(三维数组) reshape操作+order详解+numpy高维数组的读法详解

本文可能是你看过最清晰的解释......

在做机器学习的时候,

经常会遇到numpy或者其他地方的高维数组(维度d>3),这时候往往需要reshape到二维

为了保持想要的顺序不出错,需要理解:

1.numpy 高维数组的快速阅读方法

2. numpy.reshape函数的order参数的用法(算是高阶使用吧...)

1.numpy高维数组理解

先看二维数组:

2行 5列的例子
不用多说

d2=np.arange(10).reshape((2,5))
d2,d2.shape

(array([[0, 1, 2, 3, 4],
        [5, 6, 7, 8, 9]]),
 (2, 5))

再看三维数组:

快速阅读数组的方法:

(2,2,3)->先看最左边的2,理解为2行,剩下部分可以看做(2,3)大小的二维矩阵

总体理解就是:一个2行,每行包含一个2行3列的矩阵块    的矩阵

d3=np.arange(12).reshape((2,2,3))
d3,d3.shape

(array([[[ 0,  1,  2],
         [ 3,  4,  5]],
 
        [[ 6,  7,  8],
         [ 9, 10, 11]]]),
 (2, 2, 3))

推广到更高维:

这里是4维,仍然很简单,将第一个维度看做行

则是4行,每行1个元素,每个元素是一个(3,1,2)形状的矩阵

然后就降到了三维,以此类推,可以理解N维数组

d4=np.arange(24).reshape((4,3,1,2))
d4,d4.shape

(array([[[[ 0,  1]],
 
         [[ 2,  3]],
 
         [[ 4,  5]]],
 
 
        [[[ 6,  7]],
 
         [[ 8,  9]],
 
         [[10, 11]]],
 
 
        [[[12, 13]],
 
         [[14, 15]],
 
         [[16, 17]]],
 
 
        [[[18, 19]],
 
         [[20, 21]],
 
         [[22, 23]]]]),
 (4, 3, 1, 2))

2.numpy.reshape

官方文档,可以看到有一个order参数

其中,先给个数组a

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

order='C'的例子

‘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.

就是先行后列的读,然后以同样的顺序,填充到新的shape的矩阵里

np.reshape(a, (2, 3), order='C') # C-like index ordering
array([[0, 1, 2],
       [3, 4, 5]])

order='F'的例子

‘F’ means to read / write the elements using Fortran-like index order, with the first index changing fastest, and the last index changing slowest.

就是先列后行的读,然后然后以同样的顺序,填充到新的shape的矩阵里

np.reshape(a, (2, 3), order='F') # Fortran-like index ordering
array([[0, 4, 3],
       [2, 1, 5]])

order='A'的例子

‘A’ means to read / write the elements in Fortran-like index order if a is Fortran contiguous in memory, C-like order otherwise.

就是根据内存里的数据读,是什么顺序就什么顺序(C或F),然后然后以同样的顺序,填充到新的shape的矩阵里

a = np.arange(6).reshape((3, 2))
np.reshape(a, (2, 3), order='A')

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

猜你喜欢

转载自blog.csdn.net/qq_38604355/article/details/112761457