def median_kneighbour_distance(X, k=<NUM_LIT:5>):
N_all = X.shape[<NUM_LIT:0>]<EOL>k = min(k, N_all)<EOL>N_subset = min(N_all, <NUM_LIT>)<EOL>sample_idx_train = np.random.permutation(N_all)[:N_subset]<EOL>nn = neighbors.NearestNeighbors(k)<EOL>nn.fit(X[sample_idx_train, :])<EOL>d, idx = nn.kneighbors(X[sample_idx_train, :])<EOL>return np.median(d[:, -<NUM_LIT:1>])<EOL>
Calculate the median kneighbor distance.

Find the distance between a set of random datapoints and
their kth nearest neighbours. This is a heuristic for setting the
kernel length scale.