NumPy ufunc通用函数
numpy 函数 通用
2023-06-13 09:12:02 时间
NumPy 提供了两种基本的对象,即 ndarray 和 ufunc 对象。前面几节已经介绍了 ndarray,本节将介绍 Numpy。ufunc 是 universal function 的缩写,意思是 通用函数 ,它是一种能对数组的每个元素进行操作的函数。
许多 ufunc 函数都是用C语言级别实现的,因此它们的计算速度非常快。
此外,ufun 比 math 模块中的函数更灵活。math 模块的输入一般是标量,但 NumPy 中的函数可以是向量或矩阵,而利用向量或矩阵可以避免使用循环语句,这点在机器学习、深度学习中非常重要。
math.sin: 0.5169950000000005
numpy.sin: 0.05381199999999886
由此可见,numpy.sin 比 math.sin 快近 10 倍。
循环与向量运算比较充分使用 Python 的 NumPy 库中的内建函数(Built-in Function),来实现计算的向量化,可大大地提高运行速度。NumPy 库中的内建函数使用了 SIMD 指令。如下使用的向量化要比使用循环计算速度快得多。如果使用 GPU,其性能将更强大,不过 Numpy 不支持 GPU。
请看下面的代码:
import time import numpy as np x1 = np.random.rand(1000000) x2 = np.random.rand(1000000) ##使用循环计算向量点积 tic = time.process_time() dot = 0 for i in range(len(x1)): dot+= x1[i]*x2[i] toc = time.process_time() print ( dot = + str(dot) + /n for loop----- Computation time = + str(1000*(toc - tic)) + ms ) ##使用numpy函数求点积 tic = time.process_time() dot = 0 dot = np.dot(x1,x2) toc = time.process_time() print ( dot = + str(dot) + /n verctor version---- Computation time = + str(1000*(toc - tic)) + ms )
输出结果:
dot = 250215.601995
for loop Computation time = 798.3389819999998ms
dot = 250215.601995
verctor version - Computation time = 1.885051999999554ms
从运行结果上来看,使用 for 循环的运行时间大约是向量运算的 400 倍。因此,在深度学习算法中,一般都使用向量化矩阵进行运算。
23609.html
C语言NumPypython相关文章
- 在pycharm中导入torch_pycharm导入numpy出错
- pycharm导入numpy出错_pycharm安装numpy很慢
- python中dtype的使用规范_Python numpy.dtype() 使用实例
- numpy中的reshape()函数
- NumPy使用图解教程「建议收藏」
- 【Python】numpy常用API整理汇总
- python numpy数组切片_python列表切片详解
- 12 种高效 Numpy 和 Pandas 函数为你加速分析
- sklearn库的功能_numpy库
- np.zeros函数知识大全(numpy.zeros())「建议收藏」
- pytorch tensor转int_numpy和pytorch
- Matplotlib+Numpy绘图之引言
- python numpy矩阵转置_python转制
- NumPy 秘籍中文第二版:四、将 NumPy 与世界的其他地方连接
- NumPy 秘籍中文第二版:六、特殊数组和通用函数
- NumPy 秘籍中文第二版:九、使用 Cython 加速代码
- NumPy 初学者指南中文第三版:1~5
- Ubuntu 18.04安装 pyenv、pyenv-virtualenv、virtualenv、Numpy、SciPy、Pillow、Matplotlib
- Numpy索引基础操作详解
- Linux下安装Numpy的步骤(linux安装numpy)