Scalability of Approximate Nearest Neighbors in Scikit-learn

This example studies the scalability profile of approximate 10-neighbors queries using the LSHForest with n_estimators=20 and n_candidates=200 when varying the number of samples in the dataset.
The first plot demonstrates the relationship between query time and index size of LSHForest. Query time is compared with the brute force method in exact nearest neighbor search for the same index sizes. The brute force queries have a very predictable linear scalability with the index (full scan). LSHForest index have sub-linear scalability profile but can be slower for small datasets.

The second plot shows the speedup when using approximate queries vs brute force exact queries. The speedup tends to increase with the dataset size but should reach a plateau typically when doing queries on datasets with millions of samples and a few hundreds of dimensions. Higher dimensional datasets tends to benefit more from LSHForest indexing.

The break even point (speedup = 1) depends on the dimensionality and structure of the indexed data and the parameters of the LSHForest index.

The precision of approximate queries should decrease slowly with the dataset size. The speed of the decrease depends mostly on the LSHForest parameters and the dimensionality of the data.

# Parameters of the studyn_samples_min=int(1e3)n_samples_max=int(1e5)n_features=100n_centers=100n_queries=100n_steps=6n_iter=5# Initialize the range of `n_samples`n_samples_values=np.logspace(np.log10(n_samples_min),np.log10(n_samples_max),n_steps).astype(np.int)# Generate some structured datarng=np.random.RandomState(42)all_data,_=make_blobs(n_samples=n_samples_max+n_queries,n_features=n_features,centers=n_centers,shuffle=True,random_state=0)queries=all_data[:n_queries]index_data=all_data[n_queries:]# Metrics to collect for the plotsaverage_times_exact=[]average_times_approx=[]std_times_approx=[]accuracies=[]std_accuracies=[]average_speedups=[]std_speedups=[]

p1=go.Scatter(x=n_samples_values,y=average_times_approx,error_y=dict(visible=True,arrayminus=std_times_approx),line=dict(color='red',width=2),name='LSHForest')p2=go.Scatter(x=n_samples_values,y=average_times_exact,mode='lines',line=dict(color='blue',width=2),name="NearestNeighbors(algorithm='brute', metric='cosine')")layout=go.Layout(title="Impact of index size on response time for first ""nearest neighbors queries",xaxis=dict(title="n_samples"),yaxis=dict(title="Average query time in seconds"))fig=go.Figure(data=[p1,p2],layout=layout)py.iplot(fig)