什么是矢量化? [英] What is vectorization?

查看:52
本文介绍了什么是矢量化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中向量化 for 循环意味着什么?还有另一种编写嵌套 for 循环的方法吗?

What does it mean to vectorize for-loops in Python? Is there another way to write nested for-loops?

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

I am new to Python and on my research, I always come across the NumPy library.

推荐答案

Python for 循环本质上比 C 循环慢.

Python for loops are inherently slower than their C counterpart.

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

This is why numpy offers vectorized actions on numpy arrays. It pushes the for loop you would usually do in Python down to the C level, which is much faster. numpy offers vectorized ("C level for loop") alternatives to things that otherwise would need to be done in an element-wise manner ("Python level for loop).

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

numpy 向量化加法的速度提高了 70 倍.

The numpy vectorized addition was x70 times faster.

这篇关于什么是矢量化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆