Michael
Michael

Reputation: 2367

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

Problem Setup:

Required Output:

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.

Upvotes: 3

Views: 1443

Answers (2)

Michael
Michael

Reputation: 2367

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.

Upvotes: 0

Quang Hoang
Quang Hoang

Reputation: 150735

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]

Upvotes: 2

Related Questions