什么是矢量化?

2024-09-21 03:23:01 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中对for循环进行矢量化意味着什么?是否有其他方法来编写嵌套for循环?

我是Python新手,在我的研究中,我总是遇到NumPy库。


Tags: 方法numpyfor矢量化新手
2条回答

Pythonfor循环天生就比C循环慢。

这就是为什么numpynumpy数组上提供矢量化操作的原因。它将Python中通常执行的for循环推到C级,这要快得多。numpy提供了矢量化的(“C级别for循环”)替代方法,否则需要以元素方式完成(“Python级别for循环)。

import numpy as np
from timeit import Timer

li = list(range(500000))
nump_arr = np.array(li)

def python_for():
    return [num + 1 for num in li]

def numpy_add():
    return nump_arr + 1

print(min(Timer(python_for).repeat(10, 10)))
print(min(Timer(numpy_add).repeat(10, 10)))

#  0.725692612368003
#  0.010465986942008954

矢量化的加法速度快了x70倍。

这是韦斯·麦金尼的来信:

Arrays are important because they enable you to express batch operations on data without writing any for loops. This is usually called vectorization. Any arithmetic operations between equal-size arrays applies the operation elementwise.

矢量化版本:

>>> import numpy as np
>>> arr = np.array([[1., 2., 3.], [4., 5., 6.]])
>>> arr * arr
array([[  1.,   4.,   9.],
       [ 16.,  25.,  36.]])

本地Python(嵌套)列表中的循环也是这样:

>>> arr = arr.tolist()
>>> res = [[0., 0., 0.], [0., 0., 0.]]
>>> for idx1, row in enumerate(arr):
        for idx2, val2 in enumerate(row):
            res[idx1][idx2] = val2 * val2
>>> res
[[1.0, 4.0, 9.0], [16.0, 25.0, 36.0]]

这两种操作如何比较?NumPy版本需要436ns;Python版本需要3.52微秒(3520ns)。这种“小”时间上的巨大差异被称为微性能,当您处理更大的数据或重复操作数千或数百万次时,它变得非常重要。

相关问题 更多 >

    热门问题