当创建一个数组之后,还可以给它增加一个维度,这在矩阵计算中经常会用到。

    • numpy.newaxis = None None的别名,对索引数组很有用。

    【例】很多工具包在进行计算时都会先判断输入数据的维度是否满足要求,如果输入数据达不到指定的维度时,可以使用newaxis参数来增加一个维度。

    1. import numpy as np
    2. x = np.array([1, 2, 9, 4, 5, 6, 7, 8])
    3. print(x.shape) # (8,)
    4. print(x) # [1 2 9 4 5 6 7 8]
    5. y = x[np.newaxis, :]
    6. print(y.shape) # (1, 8)
    7. print(y) # [[1 2 9 4 5 6 7 8]]
    8. y = x[:, np.newaxis]
    9. print(y.shape) # (8, 1)
    10. print(y)
    11. # [[1]
    12. # [2]
    13. # [9]
    14. # [4]
    15. # [5]
    16. # [6]
    17. # [7]
    18. # [8]]
    • numpy.squeeze(a, axis=None)从数组的形状中删除单维度条目,即把shape中为1的维度去掉。
      • a表示输入的数组;
      • axis用于指定需要删除的维度,但是指定的维度必须为单维度,否则将会报错;

    在机器学习和深度学习中,通常算法的结果是可以表示向量的数组(即包含两对或以上的方括号形式[[]]),如果直接利用这个数组进行画图可能显示界面为空(见后面的示例)。我们可以利用squeeze()函数将表示向量的数组转换为秩为1的数组,这样利用 matplotlib 库函数画图时,就可以正常的显示结果了。
    【例】

    1. import numpy as np
    2. x = np.arange(10)
    3. print(x.shape) # (10,)
    4. x = x[np.newaxis, :]
    5. print(x.shape) # (1, 10)
    6. y = np.squeeze(x)
    7. print(y.shape) # (10,)

    【例】

    1. import numpy as np
    2. x = np.array([[[0], [1], [2]]])
    3. print(x.shape) # (1, 3, 1)
    4. print(x)
    5. # [[[0]
    6. # [1]
    7. # [2]]]
    8. y = np.squeeze(x)
    9. print(y.shape) # (3,)
    10. print(y) # [0 1 2]
    11. y = np.squeeze(x, axis=0)
    12. print(y.shape) # (3, 1)
    13. print(y)
    14. # [[0]
    15. # [1]
    16. # [2]]
    17. y = np.squeeze(x, axis=2)
    18. print(y.shape) # (1, 3)
    19. print(y) # [[0 1 2]]
    20. y = np.squeeze(x, axis=1)
    21. # ValueError: cannot select an axis to squeeze out which has size not equal to one

    【例】

    1. import numpy as np
    2. import matplotlib.pyplot as plt
    3. x = np.array([[1, 4, 9, 16, 25]])
    4. print(x.shape) # (1, 5)
    5. plt.plot(x)
    6. plt.show()

    更改维度 - 图1
    【例】

    1. import numpy as np
    2. import matplotlib.pyplot as plt
    3. x = np.array([[1, 4, 9, 16, 25]])
    4. x = np.squeeze(x)
    5. print(x.shape) # (5, )
    6. plt.plot(x)
    7. plt.show()

    更改维度 - 图2