use `numpy.take` to randomly select 2d points

Viewed 688

Problem Setup:

  • points - 2D numpy.array of length N.
  • centroids - 2D numpy.array that I get as an output from K-Means algorithm, of length k < N.
  • as a centroid initialization routine for an MLE algorithm, I want to assign each point in points a random centroid from centroids.

Required Output:

  • A numpy.array of shape (N, 2), of randomly chosen 2D points from centroids

My Efforts:

  1. I've tried using the numpy.take with the numpy.random.choice as shown in Code 1, but it doesn't return the desired output.

Code 1:

import numpy as np

a = np.random.randint(1, 10, 10).reshape((5, 2))
idx = np.random.choice(5, 20)
np.take(a, idx)
Out: array([6, 2, 3, 3, 8, 2, 5, 2, 6, 3, 3, 8, 6, 6, 6, 6, 8, 2, 6, 5])

From numpy.take documentation page I've learned that it chooses items from flattened array, which is not what I need.

I'd appreciate any ideas on how to accomplish this task. Thanks in advance for any help.

2 Answers

One way is sampling the indexes, and then use that to index the first dimension of centroids:

idx = np.random.choice(np.arange(len(centroids)), size=len(a))

out = centroids[idx]

A similar to @Quang Hoang's answer, but a bit more intuitive in my opinion, will be :

a = np.random.randint(1, 10, 10).reshape((5, 2))
n_sampled_points = 20
a[np.random.randint(0, a.shape[0], n_sampled_points)]

Cheers.

Related