我需要使用 numexpr 重写此代码,它正在计算矩阵数据 [rows x cols] 和向量 [1 x cols] 的欧几里得范数矩阵。
d = ((data-vec)**2).sum(axis=1)
怎么做到呢?也许还有另一种更快的方法?
我使用 hdf5 的问题,以及从中读取的数据矩阵。例如,此代码给出错误:对象未对齐。
#naive numpy solution, can be parallel?
def test_bruteforce_knn():
h5f = tables.open_file(fileName)
t0= time.time()
d = np.empty((rows*batches,))
for i in range(batches):
d[i*rows:(i+1)*rows] = ((h5f.root.carray[i*rows:(i+1)*rows]-vec)**2).sum(axis=1)
print (time.time()-t0)
ndx = d.argsort()
print ndx[:k]
h5f.close()
#using some tricks (don't work error: objects are not aligned )
def test_bruteforce_knn():
h5f = tables.open_file(fileName)
t0= time.time()
d = np.empty((rows*batches,))
for i in range(batches):
d[i*rows:(i+1)*rows] = (np.einsum('ij,ij->i', h5f.root.carray[i*rows:(i+1)*rows],
h5f.root.carray[i*rows:(i+1)*rows])
+ np.dot(vec, vec)
-2 * np.dot(h5f.root.carray[i*rows:(i+1)*rows], vec))
print (time.time()-t0)
ndx = d.argsort()
print ndx[:k]
h5f.close()
使用 numexpr: 似乎 numexpr 不理解 h5f.root.carray[i*rows:(i+1)*rows] 它必须重新分配?
import numexpr as ne
def test_bruteforce_knn():
h5f = tables.open_file(fileName)
t0= time.time()
d = np.empty((rows*batches,))
for i in range(batches):
ne.evaluate("sum((h5f.root.carray[i*rows:(i+1)*rows] - vec) ** 2, axis=1)")
print (time.time()-t0)
ndx = d.argsort()
print ndx[:k]
h5f.close()