2010-12-12 11:07:20 +08:00
|
|
|
"""
|
|
|
|
|
This script compares the performance of the Ball Tree code
|
|
|
|
|
with the cKDTree from scipy.spatial
|
2010-03-23 16:03:39 +08:00
|
|
|
|
2010-12-12 11:07:20 +08:00
|
|
|
"""
|
|
|
|
|
|
2011-09-03 18:57:53 +08:00
|
|
|
from sklearn.ball_tree import BallTree
|
2010-03-23 16:03:39 +08:00
|
|
|
import numpy as np
|
|
|
|
|
from time import time
|
|
|
|
|
|
|
|
|
|
from scipy.spatial import cKDTree
|
|
|
|
|
import pylab as pl
|
|
|
|
|
|
2010-12-12 11:07:20 +08:00
|
|
|
|
|
|
|
|
def compare_nbrs(nbrs1, nbrs2):
|
2010-03-23 16:03:39 +08:00
|
|
|
assert nbrs1.shape == nbrs2.shape
|
|
|
|
|
if(nbrs1.ndim == 2):
|
2010-12-12 11:07:20 +08:00
|
|
|
n_samples, k = nbrs1.shape
|
|
|
|
|
for i in range(n_samples):
|
2010-03-23 16:03:39 +08:00
|
|
|
for j in range(k):
|
2010-12-12 11:07:20 +08:00
|
|
|
if nbrs1[i, j] == i:
|
2010-03-23 16:03:39 +08:00
|
|
|
continue
|
2010-12-12 11:07:20 +08:00
|
|
|
elif nbrs1[i, j] not in nbrs2[i]:
|
2010-03-23 16:03:39 +08:00
|
|
|
return False
|
|
|
|
|
return True
|
|
|
|
|
elif(nbrs1.ndim == 1):
|
2010-12-12 11:07:20 +08:00
|
|
|
return np.all(nbrs1 == nbrs2)
|
2010-03-23 16:03:39 +08:00
|
|
|
|
2011-02-01 07:11:13 +08:00
|
|
|
if __name__ == '__main__':
|
|
|
|
|
n_samples = 1000
|
|
|
|
|
leaf_size = 1 # leaf size
|
|
|
|
|
k = 20
|
|
|
|
|
BT_results = []
|
|
|
|
|
KDT_results = []
|
|
|
|
|
|
|
|
|
|
for i in range(1, 10):
|
|
|
|
|
print 'Iteration %s' %i
|
|
|
|
|
n_features = i*100
|
|
|
|
|
X = np.random.random([n_samples, n_features])
|
|
|
|
|
|
|
|
|
|
t0 = time()
|
|
|
|
|
BT = BallTree(X, leaf_size)
|
|
|
|
|
d, nbrs1 = BT.query(X, k)
|
|
|
|
|
delta = time() - t0
|
|
|
|
|
BT_results.append(delta)
|
|
|
|
|
|
|
|
|
|
t0 = time()
|
|
|
|
|
KDT = cKDTree(X, leaf_size)
|
|
|
|
|
d, nbrs2 = KDT.query(X, k)
|
|
|
|
|
delta = time() - t0
|
|
|
|
|
KDT_results.append(delta)
|
|
|
|
|
|
|
|
|
|
# this checks we get the correct result
|
|
|
|
|
assert compare_nbrs(nbrs1, nbrs2)
|
|
|
|
|
|
|
|
|
|
xx = 100 * np.arange(1, 10)
|
2011-09-03 18:57:53 +08:00
|
|
|
pl.plot(xx, BT_results, label='sklearn (BallTree)')
|
2011-02-01 07:11:13 +08:00
|
|
|
pl.plot(xx, KDT_results, label='scipy (cKDTree)')
|
|
|
|
|
pl.xlabel('number of dimensions')
|
|
|
|
|
pl.ylabel('time (seconds)')
|
|
|
|
|
pl.legend()
|
|
|
|
|
pl.show()
|