Reputation: 11192
Is there any way randomly pick index of numpy array with constant interval.
For Example, I have an array with shape (1, 150) that is 5*30 elements. I want to randomly pick x indices where x<=30 for each 30 elements. So, totally I will have x*5 randomly picked indices from the array.
First, I tried with np.chocie
but I can't use np.choice
, because it doesn't look the constant interval.
I can go with loop iteration for each elements but I feel it's not the effective way.
Is there any way in numpy?
I tried this, it gives the required result. but I want to improve the code
frames_picker = np.zeros(30*5)
samples=[]
for i in range(5):
sample = (np.random.choice(frames_picker[0: 30].shape[0], 5, replace=False))+(i*30)
samples.append(sample)
samples=np.array(samples)
frames_picker[np.sort(samples)]=1
Upvotes: 1
Views: 192
Reputation: 9806
>>> np.random.choice(30, size=(5,5), replace=False) + np.arange(0, 150, 30)[:,None]
array([[ 18, 28, 13, 6, 8],
[ 40, 56, 44, 57, 32],
[ 83, 71, 65, 81, 64],
[114, 115, 97, 90, 106],
[137, 121, 129, 142, 149]])
You can then flatten and sort them. This gives you 5 random indices from each interval [0, 29], [30, 59], ..., [120, 149].
Upvotes: 2
Reputation: 2522
You can convert the 1D array to a more suitable 2D matrix and then apply sampling. For example:
data = np.array(...) # 1D array with 5*30 elements
m = np.asmatrix(np.split(data, 5)) # chunk and convert to a matrix
sample = m[np.random.randint(m.shape[0], size=30), :] # get random 30 slices from the matrix
np.ravel(sample) # convert back to 1D array
Upvotes: 0