Python numpy.power()函數使用說明
power(x, y) 函數,計算 x 的 y 次方。
示例:x 和 y 為單個數字:
import numpy as npprint(np.power(2, 3))
8
分析:2 的 3 次方。
x 為列表,y 為單個數字:
print(np.power([2,3,4], 3))
[ 8 27 64]
分析:分別求 2, 3, 4 的 3 次方。
x 為單個數字,y 為列表:
print(np.power(2, [2,3,4]))
[ 4 8 16]
分析:分別求 2的 2, 3, 4 次方。
x 和 y 為列表:
print(np.power([2,3], [3,4]))
[ 8 81]
分析:分別求 2 的 3 次方和 3 的 4 次方。
補充:有關于python3.X.X中的power()函數的使用方法和細節
該函數在求歐氏距離較為常用,手寫機器學習時候會用到比較多
函數解釋:--- power(A,B) :求A的B次方,數學等價于A^B
---其中A和B既可以是數字(標量),也可以是列表(向量)
分三種情況:1. A、B都是數字(標量)時候,就是求A的B次方In [83]: a , b = 3 ,4 In [84]: np.power(a,b) Out[84]: 812. A是列表(向量),B是數字(標量)時候,分兩個子情況:
----power(A,B):A列表(向量)中所有元素,求B的次方;
----power(B,A):生成一個長度len(A)的列表,元素為B^A次方。具體看例子
In [10]: A, B = [1,2,3],3 # 列表A的B次方:[1^3, 2^3, 3^3]In [11]: np.power(A,B) Out[11]: array([ 1, 8, 27]) # 返回len(A)長度的列表,其中元素[3^1, 3^2, 3^3]In [12]: np.power(B,A) Out[12]: array([ 3, 9, 27])3. AB都是列表(向量)時候,必須len(A)=len(B)
In [13]: A , B = [1,2,3],[4,5,6] In [14]: np.power(A,B) Out[14]: array([ 1, 32, 729]) # 如果A和B的長度不一樣,會報錯In [15]: A , B = [1,2,3],[4,5,6,7] In [16]: np.power(A,B) ValueError: operands could not be broadcast together with shapes (3,) (4,)
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。如有錯誤或未考慮完全的地方,望不吝賜教。
相關文章:
