Python如何提高numpy数组的性能?
Python How to improve numpy array performance?
我有一个全局 numpy.array data,它是一个 200*200*3 3d 数组,包含 3d-space 中的 40000 个点。
我的目标是计算每个点到单位立方体四个角的距离((0, 0, 0),(1, 0, 0),(0, 1, 0),(0 , 0, 1)), 所以我可以确定哪个角离它最近。
def dist(*point):
return np.linalg.norm(data - np.array(rgb), axis=2)
buffer = np.stack([dist(0, 0, 0), dist(1, 0, 0), dist(0, 1, 0), dist(0, 0, 1)]).argmin(axis=0)
我写了这段代码并测试了它,每次花费我大约 10ms 运行。
我的问题是如何在不到 1 毫秒的时间内提高这段代码的性能,更好地 运行。
您可以使用 Scipy cdist
-
# unit cube coordinates as array
uc = np.array([[0, 0, 0],[1, 0, 0], [0, 1, 0], [0, 0, 1]])
# buffer output
buf = cdist(data.reshape(-1,3), uc).argmin(1).reshape(data.shape[0],-1)
运行时测试
# Original approach
def org_app():
return np.stack([dist(0, 0, 0), dist(1, 0, 0), \
dist(0, 1, 0), dist(0, 0, 1)]).argmin(axis=0)
计时 -
In [170]: data = np.random.rand(200,200,3)
In [171]: %timeit org_app()
100 loops, best of 3: 4.24 ms per loop
In [172]: %timeit cdist(data.reshape(-1,3), uc).argmin(1).reshape(data.shape[0],-1)
1000 loops, best of 3: 1.25 ms per loop
我有一个全局 numpy.array data,它是一个 200*200*3 3d 数组,包含 3d-space 中的 40000 个点。
我的目标是计算每个点到单位立方体四个角的距离((0, 0, 0),(1, 0, 0),(0, 1, 0),(0 , 0, 1)), 所以我可以确定哪个角离它最近。
def dist(*point):
return np.linalg.norm(data - np.array(rgb), axis=2)
buffer = np.stack([dist(0, 0, 0), dist(1, 0, 0), dist(0, 1, 0), dist(0, 0, 1)]).argmin(axis=0)
我写了这段代码并测试了它,每次花费我大约 10ms 运行。 我的问题是如何在不到 1 毫秒的时间内提高这段代码的性能,更好地 运行。
您可以使用 Scipy cdist
-
# unit cube coordinates as array
uc = np.array([[0, 0, 0],[1, 0, 0], [0, 1, 0], [0, 0, 1]])
# buffer output
buf = cdist(data.reshape(-1,3), uc).argmin(1).reshape(data.shape[0],-1)
运行时测试
# Original approach
def org_app():
return np.stack([dist(0, 0, 0), dist(1, 0, 0), \
dist(0, 1, 0), dist(0, 0, 1)]).argmin(axis=0)
计时 -
In [170]: data = np.random.rand(200,200,3)
In [171]: %timeit org_app()
100 loops, best of 3: 4.24 ms per loop
In [172]: %timeit cdist(data.reshape(-1,3), uc).argmin(1).reshape(data.shape[0],-1)
1000 loops, best of 3: 1.25 ms per loop