[英]Numpy Uniform Distribution With Decay
I'm trying to construct a matrix of uniform distributions decaying to 0 at the same rate in each row. 我正在尝试构建一个均匀分布的矩阵,在每行中以相同的速率衰减到0。 The distributions should be between -1 and 1. What I'm looking at is to construct something that resembles:
分布应该在-1和1之间。我正在看的是构造类似于的东西:
[[0.454/exp(0) -0.032/exp(1) 0.641/exp(2)...]
[-0.234/exp(0) 0.921/exp(1) 0.049/exp(2)...]
...
[0.910/exp(0) 0.003/exp(1) -0.908/exp(2)...]]
I can build a matrix of uniform distributions using: 我可以使用以下方法构建均匀分布矩阵:
w = np.array([np.random.uniform(-1, 1, 10) for i in range(10)])
and can achieve the desired result using a for
loop with: 并且可以使用
for
循环实现所需的结果:
for k in range(len(w)):
for l in range(len(w[0])):
w[k][l] = w[k][l]/np.exp(l)
but wanted to know if there was a better way of accomplishing this. 但想知道是否有更好的方法来实现这一目标。
You can use numpy's broadcasting feature to do this: 您可以使用numpy的广播功能来执行此操作:
w = np.random.uniform(-1, 1, size=(10, 10))
weights = np.exp(np.arange(10))
w /= weights
Alok Singhal's answer is best, but as another way to do this (perhaps more explicit) you can duplicate the vector [exp(0), ...,exp(9)]
and stack them all into matrix by doing an outer product with a vector of ones. Alok Singhal的答案是最好的,但作为另一种方法(可能更明确)你可以复制向量
[exp(0), ...,exp(9)]
并通过做一个外部产品将它们全部叠加到矩阵中一个矢量。 Then divide the 'w' matrix by the new 'decay' matrix. 然后将'w'矩阵除以新的'衰变'矩阵。
n=10
w = np.array([np.random.uniform(-1, 1, n) for i in range(n)])
decay = np.outer( np.ones((n,1)), np.exp(np.arange(10)) )
result = w/decay
You could also use np.tile
for creating a matrix out of several copies of a vector. 您还可以使用
np.tile
从向量的多个副本创建矩阵。 It accomplishes the same thing as the outer product trick. 它完成了与外部产品技巧相同的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.