[Tips] python numpy 多维矩阵结构和一维结构的等价转换

假设aa是原始多维矩阵,bb是转换的一维向量,转换方式:

bb=aa.reshape(-1)

将bb转换回aa的方法是:

cc=bb.reshape(aa.shape)

验证:

>>> aa
array([[[  8,  15],
        [  0,   8],
        [-10,   0],
        [ -5,   2],
        [ -2,  -4]],

       [[  7,   4],
        [-14,   7],
        [ 20,  -7],
        [ -7, -11],
        [-18,   8]],

       [[ 26,  -3],
        [ 12,   0],
        [ -8, -19],
        [ 18, -12],
        [  3,  -5]]], dtype=int32)
>>> aa.shape
(3, 5, 2)
>>> bb=aa.reshape(-1)
>>> bb
array([  8,  15,   0,   8, -10,   0,  -5,   2,  -2,  -4,   7,   4, -14,
         7,  20,  -7,  -7, -11, -18,   8,  26,  -3,  12,   0,  -8, -19,
        18, -12,   3,  -5], dtype=int32)
>>> bb.shape
(30,)
>>> cc=bb.reshape(aa.shape)
>>> cc
array([[[  8,  15],
        [  0,   8],
        [-10,   0],
        [ -5,   2],
        [ -2,  -4]],

       [[  7,   4],
        [-14,   7],
        [ 20,  -7],
        [ -7, -11],
        [-18,   8]],

       [[ 26,  -3],
        [ 12,   0],
        [ -8, -19],
        [ 18, -12],
        [  3,  -5]]], dtype=int32)
>>> cc.shape
(3, 5, 2)
>>> aa-cc
array([[[0, 0],
        [0, 0],
        [0, 0],
        [0, 0],
        [0, 0]],

       [[0, 0],
        [0, 0],
        [0, 0],
        [0, 0],
        [0, 0]],

       [[0, 0],
        [0, 0],
        [0, 0],
        [0, 0],
        [0, 0]]], dtype=int32)
原文地址:https://www.cnblogs.com/immortalBlog/p/13791724.html