【python】numpy数组的维度增减方法

使用np.expand_dims()为数组增加指定的轴,np.squeeze()将数组中的轴进行压缩减小维度。

1.增加numpy array的维度

在操作数组情况下,需要按照某个轴将不同数组的维度对齐,这时候需要为数组添加维度(特别是将二维数组变成高维张量的情况下)。numpy提供了expand_dims()函数来为数组增加维度:

import numpy as np

a = np.array([[1,2],[3,4]])
a.shape
print(a)
>>>
"""
(2L, 2L)
[[1 2]
 [3 4]]
"""
# 如果需要在数组上增加维度,输入需要增添维度的轴即可,注意index从零还是
a_add_dimension = np.expand_dims(a,axis=0)
a_add_dimension.shape
>>> (1L, 2L, 2L)

a_add_dimension2 = np.expand_dims(a,axis=-1)
a_add_dimension2.shape
>>> (2L, 2L, 1L)


a_add_dimension3 = np.expand_dims(a,axis=1)
a_add_dimension3.shape
>>> (2L, 1L, 2L)

2.压缩维度移除轴

在数组中会存在很多轴只有1维的情况,可以使用squeeze函数来压缩冗余维度

b = np.array([[[[5],[6]],[[7],[8]]]])
b.shape
print(b)
>>>
"""
(1L, 2L, 2L, 1L)
array([[[[5],
         [6]],

        [[7],
         [8]]]])
"""

b_squeeze = b.squeeze()
b_squeeze.shape
>>>(2L, 2L)   #默认压缩所有为1的维度


b_squeeze0 = b.squeeze(axis=0)   #调用array实例的方法
b_squeeze0.shape
>>>(2L, 2L, 1L)

b_squeeze3 = np.squeeze(b, axis=3)   #调用numpy的方法
b_squeeze3.shape
>>>(1L, 2L, 2L)
https://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.squeeze.html
https://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.expand_dims.html
https://blog.csdn.net/lihanlun/article/details/79891676

pexles.com
pic from pexels.com

发布了357 篇原创文章 · 获赞 307 · 访问量 56万+

猜你喜欢

转载自blog.csdn.net/u014636245/article/details/103576637
今日推荐