Python中的通函數(shù)numpy.ufunc詳解
一、說明
numpy.ufunc是什么函數(shù)?答曰:就是numpy的函數(shù),因為numpy針對的是數(shù)組張量,因此,幾乎每一個函數(shù)都是ufunc。本文針對ufunc的屬性進行研究。
二、numpy.ufunc函數(shù)概念
2.1 numpy.ufunc簡介
在整個數(shù)組上逐個元素地操作的函數(shù)。因此,ufunc是個泛指,這些函數(shù)為數(shù)眾多。
通用函數(shù)(或簡稱 ufunc)是一種以逐個元素的方式對 ndarrays 進行操作的函數(shù),支持數(shù)組廣播、類型轉換和其他一些標準功能。也就是說,ufunc 是函數(shù)的“矢量化”包裝器,它采用固定數(shù)量的特定輸入并產(chǎn)生固定數(shù)量的特定輸出。有關通用函數(shù)的詳細信息,請參閱通用函數(shù) (ufunc) 基礎知識。
在NumPy中,通函數(shù)是numpy.ufunc
類的實例 。 許多內置函數(shù)都是在編譯的C代碼中實現(xiàn)的。 基本的ufuncs對標量進行操作,但也有一種通用類型,基本元素是子數(shù)組(向量,矩陣等), 廣播是在其他維度上完成的。也可以ufunc
使用frompyfuncopen in new window工廠函數(shù)生成自定義實例。
2.2 numpy.ufunc.nin和numpy.ufunc.nout
該函數(shù)表述出對應ufun函數(shù)的輸入?yún)?shù)數(shù)量,如下列ufunc時對應的輸入?yún)?shù)個數(shù)。
np.add.nin 2 np.multiply.nin 2 np.power.nin 2 np.exp.nin 2
該函數(shù)表述出對應ufun函數(shù)的輸出參數(shù)數(shù)量,如下列ufunc時對應的輸入?yún)?shù)個數(shù)。
np.add.nout 1 np.multiply.nout 1 np.power.nout 1 np.exp.nout 1
2.3 numpy.ufunc.nargs
numpy.ufunc對應參數(shù)的個數(shù),
np.add.nargs 3 np.multiply.nargs 3 np.power.nargs 3 np.exp.nargs 2
如np.add函數(shù)有三個參數(shù),兩個輸入,一個輸出,如下:
a = np.array([2,4,5,6]) b = np.array([2,2,3,3]) c = np.zeros((4,)) np.add( a,b,c ) print( c )
2.4 numpy.ufunc.ntypes
表明一個ufunc的輸入數(shù)據(jù)類型格式:ufunc 可以操作的數(shù)字 NumPy 類型的數(shù)量——總共有 18 種。
np.add.ntypes 18 np.multiply.ntypes 18 np.power.ntypes 17 np.exp.ntypes 7 np.remainder.ntypes 14
2.5 numpy.ufunc.type
np.add.types ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 'GG->G', 'OO->O'] np.multiply.types ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 'GG->G', 'OO->O'] np.power.types ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 'GG->G', 'OO->O'] np.exp.types ['f->f', 'd->d', 'g->g', 'F->F', 'D->D', 'G->G', 'O->O'] np.remainder.types ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'OO->O']
2.6 維度ndim和shape
表明維度的參數(shù)有兩個,array.ndim 和 array.shape,其中ndim是指張量共幾個維度,shape是指每個維度下的向量長度。比如下例:
x = np.array([1, 2, 3]) print(x.ndim) print(x.shape) y = np.zeros((2, 3, 4)) print(y.ndim) print(y.shape)
結果:
1
(3,)
3
(2, 3, 4)
三、ufunc的廣播特性
每個通函數(shù)接受數(shù)組輸入并通過在輸入上逐元素地執(zhí)行核心功能來生成數(shù)組輸出(其中元素通常是標量,但可以是用于廣義ufunc的向量或更高階子數(shù)組)。 應用標準廣播規(guī)則,以便仍然可以有效地操作不共享完全相同形狀的輸入。 廣播可以通過四個規(guī)則來理解:
- 所有輸入數(shù)組都ndimopen in new window小于最大的輸入數(shù)組,ndimopen in new window其形狀前面有1個。
- 輸出形狀的每個維度的大小是該維度中所有輸入大小的最大值。
- 如果輸入在特定維度中的大小與該維度中的輸出大小匹配,或者其值正好為1,則可以在計算中使用該輸入。
- 如果輸入的形狀尺寸為1,則該維度中的第一個數(shù)據(jù)條目將用于沿該維度的所有計算。換句話說,ufuncopen in new window的步進機械 將不會沿著該維度步進(對于該維度,步幅將為0)。
整個NumPy使用廣播來決定如何處理不同形狀的數(shù)組; 例如,所有算術運算(+
, -
,*
之間,...)ndarraysopen in new window的數(shù)組操作之前廣播。
如果上述規(guī)則產(chǎn)生有效結果,則將一組數(shù)組稱為“可廣播”到相同的形狀, 即 滿足下列條件之一:
- 數(shù)組都具有完全相同的形狀。
- 數(shù)組都具有相同的維數(shù),每個維度的長度是公共長度或1。
- 尺寸太小的數(shù)組可以使其形狀前置為長度為1的尺寸以滿足屬性2。
如果a.shape
是 (5,1),b.shape
是 (1,6),c.shape
是 (6,)并且d.shape
是 () 使得 d 是標量,則 a , b , c 和 d 都可以廣播到維度 (5, 6); 和:
- a 的作用類似于(5,6)數(shù)組,其中 [:, 0] 廣播到其他列,
- b 的作用類似于(5,6)數(shù)組,其中 b[0, :] 廣播到其他行,
- c 就像一個(1,6)數(shù)組,因此像一個(5,6)數(shù)組,其中 c[:] 廣播到每一行,最后,
- d 的作用類似于(5,6)數(shù)組,其中重復單個值。
四、函數(shù)格式
可以在通用函數(shù) (ufunc) 的文檔中找到有關 ufunc 的詳細說明。
調用ufuncs格式:
op( *x[, out], where=True, **kwargs)
將 op 應用于參數(shù) *x elementwise,廣播參數(shù)。
廣播規(guī)則是:
長度為 1 的維度可以添加到任一數(shù)組之前。
數(shù)組可以沿長度為 1 的維度重復。
參數(shù):
*xarray_like
outndarray,None,或 ndarray 和 None 的元組,可選
用于放置結果的備用數(shù)組對象;如果提供,它必須具有輸入廣播的形狀。數(shù)組元組(可能僅作為關鍵字參數(shù))的長度必須等于輸出的數(shù)量;對 ufunc 分配的未初始化輸出使用 None。
wherearray_like,可選
此條件通過輸入廣播。在條件為 True 的位置,out 數(shù)組將設置為 ufunc 結果。在其他地方,out 數(shù)組將保留其原始值。請注意,如果通過默認 out=None 創(chuàng)建未初始化的 out 數(shù)組,則其中條件為 False 的位置將保持未初始化狀態(tài)。
五、示例詳解
5.1 用輸出參數(shù)
a = np.array([2,4,5,6]) b = np.array([2,2,3,3]) c = np.zeros((4,)) np.add( a,b,c ) print( c )
5.2 行數(shù)組和列數(shù)組
a = np.arange(3) b = np.arange(3)[:, np.newaxis] print(a) print(b)
輸出:
[0 1 2]
[[0]
[1]
[2]]
5.3 廣播規(guī)則示例
a = np.arange(3) b = np.arange(3)[:, np.newaxis] print(a) print(b) s = a + b print(s)
六、ufunc后的數(shù)列運算
6.1 數(shù)列運算
在執(zhí)行ufunc運算后,常常伴隨數(shù)列運算,它們如下
__call__(*args, **kwargs) | Call self as a function. |
accumulate(array[, axis, dtype, out]) | Accumulate the result of applying the operator to all elements. |
at(a, indices[, b]) | Performs unbuffered in place operation on operand 'a' for elements specified by 'indices'. |
outer(A, B, /, **kwargs) | Apply the ufunc op to all pairs (a, b) with a in A and b in B. |
reduce(array[, axis, dtype, out, keepdims, ...]) | Reduces array's dimension by one, by applying ufunc along one axis. |
reduceat(array, indices[, axis, dtype, out]) | Performs a (local) reduce with specified slices over a single axis. |
resolve_dtypes(dtypes, *[, signature, ...]) | Find the dtypes NumPy will use for the operation. |
6.2 累計模式
累計模式不可以單獨使用,而是與add以及multiply搭配使用:
np.add.accumulate([2, 3, 5]) array([ 2, 5, 10]) np.multiply.accumulate([2, 3, 5]) array([ 2, 6, 30])
np.add.accumulate(I, 0) array([[1., 0.], [1., 1.]]) np.add.accumulate(I) # no axis specified = axis zero array([[1., 0.], [1., 1.]])
6.3 對數(shù)組中某個index的元素進行局部處理
1) 將項目 0 和 1 設置為負值:
a = np.array([1, 2, 3, 4]) np.negative.at(a, [0, 1]) print( a ) array([-1, -2, 3, 4])
2) 遞增項目 0 和 1,遞增項目 2 兩次:
a = np.array([1, 2, 3, 4]) np.add.at(a, [0, 1, 2, 2], 1) print( a ) array([2, 3, 5, 4])
3) 將第一個數(shù)組中的項 0 和 1 添加到第二個數(shù)組,并將結果存儲在第一個數(shù)組中:
a = np.array([1, 2, 3, 4]) b = np.array([1, 2]) np.add.at(a, [0, 1], b) print(a) array([2, 4, 3, 4])
6.4 outer外積
簡單數(shù)組外積
np.multiply.outer([1, 2, 3], [4, 5, 6]) array([[ 4, 5, 6], [ 8, 10, 12], [12, 15, 18]])
張量的外積
A = np.array([[1, 2, 3], [4, 5, 6]]) A.shape (2, 3) B = np.array([[1, 2, 3, 4]]) B.shape (1, 4) C = np.multiply.outer(A, B) C.shape; C (2, 3, 1, 4) array([[[[ 1, 2, 3, 4]], [[ 2, 4, 6, 8]], [[ 3, 6, 9, 12]]], [[[ 4, 8, 12, 16]], [[ 5, 10, 15, 20]], [[ 6, 12, 18, 24]]]])
6.5 reduce方法
a = np.multiply.reduce([2,3,5]) print( a) 30
X = np.arange(8).reshape((2,2,2)) X array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) np.add.reduce(X, 0) array([[ 4, 6], [ 8, 10]]) np.add.reduce(X) # confirm: default axis value is 0 array([[ 4, 6], [ 8, 10]]) np.add.reduce(X, 1) array([[ 2, 4], [10, 12]]) np.add.reduce(X, 2) array([[ 1, 5], [ 9, 13]])
您可以使用 initial 關鍵字參數(shù)以不同的值初始化縮減,以及在何處選擇要包含的特定元素:
np.add.reduce([10], initial=5) 15 np.add.reduce(np.ones((2, 2, 2)), axis=(0, 2), initial=10) array([14., 14.]) a = np.array([10., np.nan, 10]) np.add.reduce(a, where=~np.isnan(a)) 20.0
np.minimum.reduce([], initial=np.inf) inf np.minimum.reduce([[1., 2.], [3., 4.]], initial=10., where=[True, False]) array([ 1., 10.]) np.minimum.reduce([]) Traceback (most recent call last):
到此這篇關于什么是通函數(shù)numpy.ufunc的文章就介紹到這了,更多相關通函數(shù)numpy.ufunc內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
舉例講解Python中的list列表數(shù)據(jù)結構用法
這篇文章主要介紹了Python中的list列表數(shù)據(jù)結構用法,列表是Python內置的六種集合類數(shù)據(jù)類型中最常見的之一,需要的朋友可以參考下2016-03-03Python的Django框架中的數(shù)據(jù)過濾功能
這篇文章主要介紹了Python的Django框架中的數(shù)據(jù)過濾功能,為更新數(shù)據(jù)庫數(shù)據(jù)時的數(shù)據(jù)查找提供了方便,需要的朋友可以參考下2015-07-0710 行 Python 代碼教你自動發(fā)送短信(不想回復工作郵件妙招)
這篇文章主要介紹了10 行 Python 代碼教你自動發(fā)送短信(不想回復工作郵件妙招),目前在國內通過手機短信保障信息安全是比較常見的,具體實例代碼大家跟隨小編一起通過本文學習吧2018-10-10Python接口自動化淺析logging封裝及實戰(zhàn)操作
本篇文章主要給大家介紹將了logging常用配置放入yaml配置文件、logging日志封裝及結合登錄用例,講解日志如何在接口測試中運用的實例操作2021-08-08