2017-08-01 30 views
2

我有一个全球numpy.array 数据这是一个200 * 200 * 3的三维阵列在三维空间中包含40000点。 (0,0,0),(1,0,0),(0,1,0),(0,0,0,0),(1,0,0,0,0), 0,1)),所以我可以确定哪个角落离它最近。Python如何提高numpy数组的性能?

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。 我的问题是如何提高这段代码的性能,更好地在不到1ms的时间内运行。

+0

不立方体有超过4个角? –

+1

@JohnZwinck只需要计算其中四个的距离。 – iouvxz

回答

3

你可以使用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