Reputation: 11171
How can I do the following in Python?
x
, and associated probability density function (pdf) p(x)
N
elements randomly, as specified by p(x)
x
with selected elements removed (x
will be shorter)caveat: array x
may have repeated values, xi
, that nevertheless have different probabilities (p(x)
actually depends on parameters I'm not showing), so I want to be sure to remove the "correct" one that was chosen, not just elements that share the same value xi
.
My code thusfar:
import numpy as np
N = 5;
x = np.linspace(0,5,11)
pdf = np.exp(-x**2);
pdf = pdf/np.sum(pdf);
x_rand_sorted = np.random.choice(x,N,replace=False,p = pdf)
print 'x:',x
print 'first N random elements:', x_rand_sorted
print 'x without random elements = ??'
Upvotes: 1
Views: 2639
Reputation: 11171
Outputs:
x_remaining
N
random elements: x_rand_vals
randices
Example:
import numpy as np
N = 9;
n = 4;
x = np.linspace(0,2,N);
pdf = np.exp(-x**2);
pdf = pdf/np.sum(pdf);
#create mask, choose random indices from x according to pdf, set chosen indices to True:
indices = np.full(x.shape, False, bool)
randices = np.random.choice(np.arange(indices.shape[0]), n, replace = False,p = pdf)
indices[randices] = True
x_rand_vals = x[randices]
x_remaining = x[~indices]
np.set_printoptions(precision=3)
print 'original x:\t\t', x
print 'pdf array:\t\t', pdf
print 'random indices:\t\t',randices
print 'random values:\t\t',x_rand_vals
print 'remaining array:\t',x_remaining
(example output):
original x: [ 0. 0.2 0.4 0.6 0.8 1. 1.2 1.4 1.6 1.8 2. ]
random indices: [4 2 5]
random values: [ 0.8 0.4 1. ]
remaining array: [ 0. 0.2 0.6 1.2 1.4 1.6 1.8 2. ]
Upvotes: 1
Reputation: 11602
You can use a boolean mask:
import numpy as np
N = 5;
x = np.linspace(0,5,11)
pdf = np.exp(-x**2);
pdf = pdf/np.sum(pdf);
index = np.full(x.shape, False, bool)
index[np.random.choice(np.arange(index.shape[0]), N, replace = False,p = pdf)] = True
x_rand_sorted = x[index]
x_rand_remaining = x[~index]
print 'x:',x
print 'first N random elements:', x_rand_sorted
print 'x without random elements: ', x_rand_remaining
Upvotes: 1