使用
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.htmlhttps://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.expand_dims.html
https://blog.csdn.net/lihanlun/article/details/79891676