Numpy矩阵维度操作详解:np.expand_dims、np.newaxis与np.squeeze用法

青禾
青禾
发布时间:2026-10-14 | 2人浏览过
原创

本文详细解析Numpy中矩阵维度变更的核心方法。通过np.newaxis和np.expand_dims实现矩阵维度的扩充,支持指定轴添加新维度;利用np.squeeze函数移除形状中大小为1的维度,可指定特定轴或自动处理所有单维。文章包含完整代码示例与输出结果,涵盖正常操作及异常处理场景,帮助开发者精准控制数组形状。

Numpy矩阵维度操作概述

在处理矩阵数据时,各类接口对输入矩阵的维度要求存在差异,输入数据可能是一维(1-D)、二维(2-D)或三维(3-D)等不同形式。为了适应不同的计算需求,掌握Numpy中矩阵维度变更的方法至关重要。主要涉及以下三种操作方式:

1、使用np.newaxis扩充矩阵维度

2、使用np.expand_dims扩充矩阵维度

3、使用np.squeeze删除矩阵中维度大小为1的维度

使用np.newaxis和np.expand_dims扩充维度

关于np.newaxis和np.expand_dims扩充矩阵维度的具体实现:


import numpy as np
 
x = np.arange(8).reshape(2, 4)
print(x.shape)
 
# 添加第0维,输出shape -> (1, 2, 4)
x1 = x[np.newaxis, :]
print(x1.shape)
 
# 添加第1维, 输出shape -> (2, 1, 4)
x2 = np.expand_dims(x, axis=1)
print(x2.shape)

执行上述代码后的输出结果如下:

(2, 4) (1, 2, 4) (2, 1, 4)

使用np.squeeze降低矩阵维度

使用npsqueeze降低矩阵维度的操作示例:


"""
 squeeze 函数:从数组的形状中删除单维度条目,即把shape中为1的维度去掉
 用法:numpy.squeeze(a,axis = None)
  1)a表示输入的数组;
  2)axis用于指定需要删除的维度,但是指定的维度必须为单维度,否则将会报错;
  3)axis的取值可为None 或 int 或 tuple of ints, 可选。若axis为空,则删除所有单维度的条目;
  4)返回值:数组
  5) 不会修改原数组;
"""
import numpy as np 
print("#" * 40, "原始数据", "#" * 40)
x = np.arange(10).reshape(1, 1, 10, 1)
print(x.shape)
print(x)
 
print("#" * 40, "去掉axis=0这个维度", "#" * 40)
x_squeeze_0 = np.squeeze(x, axis=0)
print(x_squeeze_0.shape, x_squeeze_0)
 
print("#" * 40, "去掉axis=3这个维度", "#" * 40)
x_squeeze_3 = np.squeeze(x, axis=3)
print(x_squeeze_3.shape, x_squeeze_3)
 
print("#" * 40, "去掉axis=0, axis=1这两个维度", "#" * 40)
x_squeeze_0_1 = np.squeeze(x, axis=(0, 1))
print(x_squeeze_0_1.shape, x_squeeze_0_1)
 
print("#" * 40, "去掉所有1维的维度", "#" * 40)
x_squeeze = np.squeeze(x)
print(x_squeeze.shape, x_squeeze)
 
print("#" * 40, "去掉不是1维的维度,抛异常", "#" * 40)
try:
 x_squeeze = np.squeeze(x, axis=2)
 print(x_squeeze.shape, x_squeeze)
except Exception as e:
 print(e)

相关操作的输出结果展示:

######################################## 原始数据 ######################################## (1, 1, 10, 1) [[[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]]] ######################################## 去掉axis=0这个维度 ######################################## (1, 10, 1) [[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]] ######################################## 去掉axis=3这个维度 ######################################## (1, 1, 10) [[[0 1 2 3 4 5 6 7 8 9]]] ######################################## 去掉axis=0, axis=1这两个维度 ######################################## (10, 1) [[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]] ######################################## 去掉所有1维的维度 ######################################## (10,) [0 1 2 3 4 5 6 7 8 9] ######################################## 去掉不是1维的维度,抛异常 ######################################## cannot select an axis to squeeze out which has size not equal to one

参考链接

至此,关于详解Numpy扩充矩阵维度(np.expand_dims, np.newaxis)和删除维度(np.squeeze)的方法介绍完毕。如需了解更多Numpy矩阵维度和删除维度的相关内容,建议搜索本站历史文章或继续浏览后续相关文章,感谢大家的支持!

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表