【问题标题】:Python - Fastest / Best way to apply a function to each element of a numpy.arrayPython - 将函数应用于 numpy.array 的每个元素的最快/最佳方法
【发布时间】:2018-07-06 21:31:18
【问题描述】:

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

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

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))

【问题讨论】:

  • 只对整个数组进行所有操作,而不是使用向量化! (如 x += 1)
  • 你能发表你的意思作为答案吗?
  • 总有一天会有人的。但老实说:你花了 5 分钟看文档吗?您的函数非常适合利用 numpy 的矢量化操作。不需要循环。文档还警告 np.vectorize (有点隐藏循环)!解决方案或多或少是相同的代码,只是对数组 x 本身进行操作。没有包装。
  • 正如@sascha 提到的,如果每个元素操作都是独立的并且f(M(m, n)) = N(m, n),即输入和输出是相同的形状数组,那么只需应用整个数组的函数。一些简单的例子是,对于数组 A,np.abs(A)A**2A - 52*A 等。
  • 谢谢!我尝试重新发明轮子 :) 我会尝试花时间在文档上

标签: python arrays numpy vectorization


【解决方案1】:

正如@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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-15
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    相关资源
    最近更新 更多