如何在Python中执行以下操作?
x
开始,以及相关的概率密度函数(pdf)p(x)
N
p(x)
个元素
x
,删除所选元素(x
将更短)警告:数组x
可能有重复的值xi
,但它们有不同的概率(p(x)
实际上取决于我没有显示的参数),所以我想确定删除所选的“正确”的,而不仅仅是具有相同值xi
的元素。
我的代码因此:
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 = ??'
答案 0 :(得分:1)
您可以使用布尔掩码:
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
答案 1 :(得分:1)
输出:
x_remaining
N
随机元素:x_rand_vals
randices
示例:
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
(示例输出):
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. ]