np.newaxis()函數(shù)的具體使用
np.newaxis
np.newaxis 的功能是增加新的維度,但是要注意 np.newaxis 放的位置不同,產(chǎn)生的矩陣形狀也不同。
通常按照如下規(guī)則:
np.newaxis 放在哪個位置,就會給哪個位置增加維度
- x[:, np.newaxis] ,放在后面,會給列上增加維度
- x[np.newaxis, :] ,放在前面,會給行上增加維度
用途: 通常用它將一維的數(shù)據(jù)轉換成一個矩陣,這樣就可以與其他矩陣進行相乘。
例1:這里的 x 是一維數(shù)據(jù),其 shape 是 4,可以看到通過在列方向上增加新維度,變成了 4 x 1 的矩陣,也就是在 shape 的后面發(fā)生了變化。
x = np.array([1, 2, 3, 4]) print(x.shape) x_add = x[:, np.newaxis] print(x_add.shape) print(x_add) >>> (4,) (4, 1) [[1] ?[2] ?[3] ?[4]]
例2:通過在行方向上增加新的維度,變成了 1 x 4 的矩陣,也就是在 shape 的前面發(fā)生了變化。
x = np.array([1, 2, 3, 4]) print(x.shape) x_add = x[np.newaxis, :] print(x_add.shape) print(x_add) >>> (4,) (1, 4) [[1 2 3 4]]
例3:給矩陣增加一個維度。
x = np.array([[1, 2, 3, 4], [2, 3, 4, 5]]) print(x.shape) x_add = x[:, np.newaxis] print(x_add) print(x_add.shape) >>> (2, 4) [[[1 2 3 4]] ?[[2 3 4 5]]] (2, 1, 4)
到此這篇關于np.newaxis()函數(shù)的具體使用的文章就介紹到這了,更多相關np.newaxis使用內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python json 遞歸打印所有json子節(jié)點信息的例子
今天小編就為大家分享一篇python json 遞歸打印所有json子節(jié)點信息的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
python在Windows下安裝setuptools(easy_install工具)步驟詳解
這篇文章主要介紹了python在Windows下安裝setuptools(easy_install工具)步驟,簡單介紹了setuptools并分析了其安裝步驟與所涉及的相關軟件,需要的朋友可以參考下2016-07-07

