• numpy 代码优化(一)—— 常见手段


    选择使用 numpy 库的应有之义就在于:应当以矢量化的方式(vectorized operations)来避免迭代操作(iterations),numpy 下的迭代操作执行起来十分耗时。

    import numpy as np
    
    x = np.linspace(0, 8*np.pi, 100)
    y = np.cos(x)
    
    # 一种矢量化的修改方式
    x[y > 0] = 100

    0. Python 中的循环

    Python 是一种比 C/C# 更为动态的语言。Python 中的循环之所以执行较慢的原因在于,每进入一次循环,CPython 解释器都将执行一些额外的且费时的工作, specifically, it is binding the name x with the next object from the iterator, then when it evaluates the assignment it has to look up the name x again.

    1. np.ndarray 为效率而设计的成员函数:

    • np.ndarray.fill()(通过 C 或者 Fortran 实现):执行多维数组初始化的动作,注意 fill() 函数不是 np 下的全局函数,而是 ndarray 的成员函数;

    2. nditer:numpy 下高效的迭代操作

  • 相关阅读:
    【项目】项目75
    【项目】项目74
    【项目】项目73
    【项目】项目72
    【项目】项目71
    【项目】项目70
    【项目】项目69
    【项目】项目68
    【项目】项目67
    .Net随笔:解决VS2008,重新生成解决方案,很慢
  • 原文地址:https://www.cnblogs.com/mtcnn/p/9422244.html
Copyright © 2020-2023  润新知