脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 给numpy.array增加维度的超简单方法

给numpy.array增加维度的超简单方法

2021-11-19 13:49whyume Python

这篇文章主要介绍了给numpy.array增加维度的超简单方法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

输入:

?
1
2
3
import numpy as np
a = np.array([1, 2, 3])
print(a)

输出结果:

array([1, 2, 3])

输入:

?
1
print(a[None])

输出结果:

array([[1, 2, 3]])

输入:

?
1
print(a[:,None])

输出结果:

array([[1],               
       [2],               
       [3]])     

numpy数组的维度增减方法

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

1.增加numpy array的维度

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

numpy提供了expand_dims()函数来为数组增加维度:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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函数来压缩冗余维度

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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://blog.csdn.net/whyume/article/details/79900457

延伸 · 阅读

精彩推荐