給numpy.array增加維度的超簡單方法
輸入:
import numpy as np a = np.array([1, 2, 3]) print(a)
輸出結(jié)果:
array([1, 2, 3])
輸入:
print(a[None])
輸出結(jié)果:
array([[1, 2, 3]])
輸入:
print(a[:,None])
輸出結(jié)果:
array([[1],
[2],
[3]])
numpy數(shù)組的維度增減方法
使用np.expand_dims()為數(shù)組增加指定的軸,np.squeeze()將數(shù)組中的軸進行壓縮減小維度。
1.增加numpy array的維度
在操作數(shù)組情況下,需要按照某個軸將不同數(shù)組的維度對齊,這時候需要為數(shù)組添加維度(特別是將二維數(shù)組變成高維張量的情況下)。
numpy提供了expand_dims()函數(shù)來為數(shù)組增加維度:
import numpy as np a = np.array([[1,2],[3,4]]) a.shape print(a) >>> """ (2L, 2L) [[1 2] [3 4]] """ # 如果需要在數(shù)組上增加維度,輸入需要增添維度的軸即可,注意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.壓縮維度移除軸
在數(shù)組中會存在很多軸只有1維的情況,可以使用squeeze函數(shù)來壓縮冗余維度
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) #默認(rèn)壓縮所有為1的維度
b_squeeze0 = b.squeeze(axis=0) #調(diào)用array實例的方法
b_squeeze0.shape
>>>(2L, 2L, 1L)
b_squeeze3 = np.squeeze(b, axis=3) #調(diào)用numpy的方法
b_squeeze3.shape
>>>(1L, 2L, 2L)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python中threading庫實現(xiàn)線程鎖與釋放鎖
threading用于提供線程相關(guān)的操作,為了保證安全的訪問一個資源對象,我們需要創(chuàng)建鎖。那么Python線程鎖與釋放鎖如何實現(xiàn),感興趣的小伙伴們可以參考一下2021-05-05
Matplotlib animation模塊實現(xiàn)動態(tài)圖
這篇文章主要介紹了Matplotlib animation模塊實現(xiàn)動態(tài)圖,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02
PyCharm 2020.2下配置Anaconda環(huán)境的方法步驟
這篇文章主要介紹了PyCharm 2020.2下配置Anaconda環(huán)境的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09

