Python - 将函数应用于numpy.array的每个元素的最快/最佳方法



我想知道将函数应用于numpy数组的每个元素的最快(或"最佳"(方法是什么。我用更大的数据集尝试了这种方法,这需要相当长的时间......使用您在我的实现和您的实现中获得的结果(以毫秒为单位(发布您的答案,因为不同的硬件会在同一代码上给出不同的结果

请在 2 个注释行之间分享您的实现

import numpy as np
import time
# Some random data
x = np.random.rand(5,32,32,3)*255
x = x.astype(int)
# Defining some function
def normalize(x, a=0, b=1, x_min=0, x_max=255):
    return a + (x - x_min)*(b - a)/(x_max-x_min)
## Start timer
start_time = time.time()
# ---------------------IMPLEMENTATION---------------------
# Apply Normalize function to each element in the array
n = np.vectorize(normalize)
x = n(x)
#_________________________________________________________
# Stop timer and show time in milliseconds
elapsed_time = time.time() - start_time
print("Time [ms] = " + str(elapsed_time*1000))

正如 @sascha 所指出的,我只需要将函数应用于整个数组:

import numpy as np
import time
# Some random data
x = np.random.rand(5,32,32,3)*255
x = x.astype(int)
# Defining some function
def normalize(x, a=0, b=1, x_min=0, x_max=255):
    return a + (x - x_min)*(b - a)/(x_max-x_min)
## Start timer
start_time = time.time()
# ---------------------IMPLEMENTATION---------------------
# Apply Normalize function to each element in the array
x = normalize(x)
#_________________________________________________________
# Stop timer and show time in milliseconds
elapsed_time = time.time() - start_time
print("Time [ms] = " + str(elapsed_time*1000))

最新更新