什么是向量化?向量化是在数据集上实现(numpy)数组操作的技术。在后台,它对数组或系列的所有元素一次性进行操作(不像'for'循环那样一次操作一行)。
在这篇博客中,我们将看看一些用例,在这些用例中,我们可以很容易地用向量化代替python循环。这将帮助你节省时间,并在编码方面变得更加熟练。
使用案例1:寻找数字的总和首先,我们来看看一个基本的例子,即在python中使用循环和向量来寻找数字的总和。
使用循环import time start = time.time() # 遍历之和 total = 0 # 遍历150万个数字 for item in range(0, 1500000): total = total + item print('sum is:' + str(total)) end = time.time() print(end - start) #1124999250000 #0.14 seconds
使用向量化import numpy as np start = time.time() # 向量化和--使用numpy进行向量化 # np.range创建从0到1499999的数字序列 print(np.sum(np.arange(1500000))) end = time.time() print(end - start) ##1124999250000 ##0.008 seconds
与使用范围函数的迭代相比,向量化的执行时间约18倍。在使用pandas dataframe时,这种差异将变得更加明显。
使用案例2:dataframe数学运算在数据科学中,当使用pandas dataframe时,开发者会使用循环来创建新的数学运算的派生列。
在下面的例子中,我们可以看到,在这样的用例中,循环可以很容易地被向量化所取代。
创建dataframedataframe是以行和列的形式存在的表格数据。
我们正在创建一个有500万行和4列的pandas dataframe,其中充满了0到50之间的随机值。
import numpy as np import pandas as pd df = pd.dataframe(np.random.randint(0, 50, size=(5000000, 4)), columns=('a','b','c','d')) df.shape # (5000000, 5) df.head()
我们将创建一个新的列'ratio',以找到列'd'和'c'的比率。
使用循环import time start = time.time() # iterating through dataframe using iterrows for idx, row in df.iterrows(): # creating a new column df.at[idx,'ratio'] = 100 * (row[d] / row[c]) end = time.time() print(end - start) ### 109 seconds
使用向量化start = time.time() df[ratio] = 100 * (df[d] / df[c]) end = time.time() print(end - start) ### 0.12 seconds
我们可以看到dataframe有了明显的改进,与python中的循环相比,向量化几乎快了1000倍。
使用案例3:dataframe上if-else语句我们实现了很多需要我们使用 if-else 类型逻辑的操作。我们可以很容易地用python中的向量化操作代替这些逻辑。
看一下下面的例子来更好地理解它(我们将使用在用例2中创建的dataframe)。
想象一下,如何根据退出的列'a'的一些条件来创建一个新的列'e'。
使用循环import time start = time.time() # iterating through dataframe using iterrows for idx, row in df.iterrows(): if row.a == 0: df.at[idx,'e'] = row.d elif (row.a 0): df.at[idx,'e'] = (row.b)-(row.c) else: df.at[idx,'e'] = row.b + row.c end = time.time() print(end - start) ### time taken: 177 seconds
使用向量化start = time.time() df['e'] = df['b'] + df['c'] df.loc[df['a'] >> import numpy as np >>> # 设置 m 的初始值 >>> m = np.random.rand(1,5) array([[0.49976103, 0.33991827, 0.60596021, 0.78518515, 0.5540753]]) >>> # 500万行的输入值 >>> x = np.random.rand(5000000,5)
使用循环import numpy as np m = np.random.rand(1,5) x = np.random.rand(5000000,5) total = 0 tic = time.process_time() for i in range(0,5000000): total = 0 for j in range(0,5): total = total + x[i][j]*m[0][j] zer[i] = total toc = time.process_time() print (computation time = + str((toc - tic)) + seconds) ####computation time = 28.228 seconds
使用向量化
tic = time.process_time() #dot product np.dot(x,m.t) toc = time.process_time() print (computation time = + str((toc - tic)) + seconds) ####computation time = 0.107 seconds
np.dot在后端实现了向量的矩阵乘法。与python中的循环相比,它的速度提高了165倍。
写在最后python中的向量化是非常快的,当在处理非常大的数据集时,建议你应该优先考虑向量化而不是循环。这样,随着时间的推移,你会逐渐习惯于按照向量化的思路来编写代码。
以上就是再见!python 循环,向量化已超神的详细内容。