创建一个Numpy矩阵,存储输入ndarray

时间:2017-08-23 17:58:15

标签: python numpy random vectorization scientific-computing

我有一个名为weights形状的2d ndarray(npts,nweights)。对于weights的每个,我希望随机地对行进行随机播放。我想重复这个过程num_shuffles次,并将shuffling集合存储到名为weights_matrix的3d ndarray中。重要的是,对于每次改组迭代,weights的每列的混洗索引应该相同。

下面显示了该算法的显式天真双循环实现。是否有可能避免python循环并在纯Numpy中生成weights_matrix

import numpy as np 
npts, nweights = 5, 2
weights = np.random.rand(npts*nweights).reshape((npts, nweights))

num_shuffles = 3
weights_matrix = np.zeros((num_shuffles, npts, nweights))
for i in range(num_shuffles):
    indx = np.random.choice(np.arange(npts), npts, replace=False)
    for j in range(nweights):
        weights_matrix[i, :, j] = weights[indx, j]

2 个答案:

答案 0 :(得分:1)

您可以首先使用原始权重的副本填充3-D数组,然后对该3-D数组的切片执行简单迭代,使用random.shuffle对每个2-D切片进行适当的混洗

  

对于每一列权重,我希望随机改变行...每列权重的改组索引应该相同

只是另一种说法“我想随机重新排序2D数组的行”。 import numpy weights = numpy.array( [ [ 1, 2, 3 ], [ 4, 5, 6], [ 7, 8, 9 ] ] ) weights_3d = weights[ numpy.newaxis, :, : ].repeat( 10, axis=0 ) for w in weights_3d: numpy.random.shuffle( w ) # in-place shuffle of the rows of each slice print( weights_3d[0, :, :] ) print( weights_3d[1, :, :] ) print( weights_3d[2, :, :] ) 是一个支持numpy-array的<ul> <li class="email__ {active--: showEmail} {disabled--: !hasEmailMsg}" onClick={hasEmailMsg: handlePreviewChange('email')} ></li> <li class="mobile__ {active--: showMobile} {disabled--: !hasMobileMsg}" onClick={hasMobileMsg: handlePreviewChange('mobile')} ></li> </ul> 版本:它将对就地容器的元素进行重新排序。这就是你所需要的,因为在这个意义上,二维numpy数组的“元素”就是它的行。

hasEmailMsg

答案 1 :(得分:1)

这是一个矢量化解决方案,其思想借鉴于this post -

weights[np.random.rand(num_shuffles,weights.shape[0]).argsort(1)]

示例运行 -

In [28]: weights
Out[28]: 
array([[ 0.22508764,  0.8527072 ],
       [ 0.31504052,  0.73272155],
       [ 0.73370203,  0.54889059],
       [ 0.87470619,  0.12394942],
       [ 0.20587307,  0.11385946]])

In [29]: num_shuffles = 3

In [30]: weights[np.random.rand(num_shuffles,weights.shape[0]).argsort(1)]
Out[30]: 
array([[[ 0.87470619,  0.12394942],
        [ 0.20587307,  0.11385946],
        [ 0.22508764,  0.8527072 ],
        [ 0.31504052,  0.73272155],
        [ 0.73370203,  0.54889059]],

       [[ 0.87470619,  0.12394942],
        [ 0.22508764,  0.8527072 ],
        [ 0.73370203,  0.54889059],
        [ 0.20587307,  0.11385946],
        [ 0.31504052,  0.73272155]],

       [[ 0.73370203,  0.54889059],
        [ 0.31504052,  0.73272155],
        [ 0.22508764,  0.8527072 ],
        [ 0.20587307,  0.11385946],
        [ 0.87470619,  0.12394942]]])