• 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)
  • 相关阅读:
    Shell命令之文本操作
    乘法表
    万年历
    猜数游戏
    Linux下如何进行FTP安装与设置
    CentOS 安装nload(流量统计)
    linux下创建用户并且限定用户主目录
    ftp 解决不能上传问题
    【题解】[TJOI2018]数学计算
    【平衡树做题记录】
  • 原文地址:https://www.cnblogs.com/zhoudayang/p/5153589.html
Copyright © 2020-2023  润新知