How k-nearest neighbors works