生成一个集合为1的随机变量数组(正负)

时间:2021-08-18 01:32:15

I am trying to create a numpy array with random variables that sum up to 1, but I also want to include negative values.

我正在尝试创建一个带有随机变量的numpy数组,这些变量的总和为1,但是我还想包含负值。

I am trying:

我尝试:

size =(50,1)
w = np.array(np.random.random(size))

to create the array and populate with numbers (negative and positive), and this works fine.

创建数组并填充数字(负数和正数),这很好。

Now I am trying to make them sum up to 1 with:

现在我想让它们的总和是1:

w /= np.sum(w)

But this changes my values to be all positive (eliminating the negative values).

但这改变了我的值都是正值(去掉了负值)。

What is the proper way to do an array like this?

这样做数组的正确方法是什么?

Edit: I already tried random.int and random.uniform, but the problem is that those don't sum up to 1. and if I use w /= np.sum(w) to make sure they sum up to one, it just returns positive values.

编辑:我已经尝试过随机。int和随机。统一的,但问题是这些不等于1。如果我用w /= np.sum(w)来确定它们的和是1,它会返回正值。

2 个解决方案

#1


4  

Your problem isn't your normalization, it's your random generator. np.random.random always generates positive floats from (0,1). If you want negative numbers, you'll have to change that.

你的问题不是标准化,而是你的随机生成器。np.random。随机总是产生正的浮点数(0,1)。如果你想要负数,你必须改变它。

w = np.random.random(size)*2-1
w /= w.sum()

w

array([[ 0.05377353],
       [ 0.11272973],
       [ 0.00789277],
       ..., 
       [ 0.06874176],
       [-0.12505825],
       [-0.15924267]])

w.sum()
 1.0

#2


1  

There is no built-in function specifically for this task but you can generate an array (2d preferably) based on your expected size then choose those that sum up to 1.

这个任务没有特定的内置函数,但是您可以根据预期大小生成一个数组(最好是2d),然后选择那些总和为1的数组。

Here is an example:

这是一个例子:

In [18]: arr = np.random.randint(-10, 10, (50, 5))

In [19]: arr[arr.sum(1) == 1]
Out[19]: 
array([[  9,  -9,   1,   5,  -5],
       [-10,   5,  -4,   9,   1],
       [  1,  -2,   5,   3,  -6]])

#1


4  

Your problem isn't your normalization, it's your random generator. np.random.random always generates positive floats from (0,1). If you want negative numbers, you'll have to change that.

你的问题不是标准化,而是你的随机生成器。np.random。随机总是产生正的浮点数(0,1)。如果你想要负数,你必须改变它。

w = np.random.random(size)*2-1
w /= w.sum()

w

array([[ 0.05377353],
       [ 0.11272973],
       [ 0.00789277],
       ..., 
       [ 0.06874176],
       [-0.12505825],
       [-0.15924267]])

w.sum()
 1.0

#2


1  

There is no built-in function specifically for this task but you can generate an array (2d preferably) based on your expected size then choose those that sum up to 1.

这个任务没有特定的内置函数,但是您可以根据预期大小生成一个数组(最好是2d),然后选择那些总和为1的数组。

Here is an example:

这是一个例子:

In [18]: arr = np.random.randint(-10, 10, (50, 5))

In [19]: arr[arr.sum(1) == 1]
Out[19]: 
array([[  9,  -9,   1,   5,  -5],
       [-10,   5,  -4,   9,   1],
       [  1,  -2,   5,   3,  -6]])