python中numpy對函數進行矢量化轉換


  在對numpy的數組進行操作時,我們應該盡量避免循環操作,盡可能利用矢量化函數來避免循環.

  但是,直接將自定義函數應用在numpy數組之上會報錯,我們需要將函數進行矢量化轉換.

def Theta(x):
    """
    Scalar implemenation of the Heaviside step function.
    """
    if x >= 0:
        return 1
    else:
        return 0
Theta(array([-3,-2,-1,0,1,2,3]))

  出錯信息:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-9-6658efdd2f22> in <module>()
----> 1 Theta(array([-3,-2,-1,0,1,2,3]))

<ipython-input-8-9a0cb13d93d4> in Theta(x)
      3     Scalar implemenation of the Heaviside step function.
      4     """
----> 5     if x >= 0:
      6         return 1
      7     else:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

  為了得到矢量的Theta,我們可以使用Numpy函數vectorize。在許多情況下它可以自動矢量化一個函數:

Theta_vec = vectorize(Theta)
Theta_vec(array([-3,-2,-1,0,1,2,3]))
array([0, 0, 0, 1, 1, 1, 1])

  我們也可以使用該函數從頭來接受矢量輸入(需要更多工作但是也表現更好):

def Theta(x):
    """
    Vector-aware implemenation of the Heaviside step function.
    """
    return 1 * (x >= 0)
Theta(array([-3,-2,-1,0,1,2,3]))
array([0, 0, 0, 1, 1, 1, 1])
# 對標量依然行得通
Theta(-1.2), Theta(2.6)
(0, 1)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM