Numpy:如何生成特定数组(迭代器会更好)

Numpy: How to produce a specific array (an iterator would be even better)

我需要一个数组或迭代器来循环,具有以下特征:

1° 我有一组大小为 $n$ 的 $d$ 向量(随机,排序),比如说 x[0],...,x[d-1]。

2° 我希望每个迭代值都是一个向量 od 大小 $d$,以及来自上述向量的潜在值的所有组合。这意味着:

y[0]       : [x[0,0], x[1,0],....,x[d-1,0]]
y[1]       : [x[0,1], x[1,0],....,x[d-1,0]]
y[2]       : [x[0,0], x[1,1],....,x[d-1,0]]
...
y[-1]      : [x[0,n-1], x[1,n-1],...., x[d-1,n-1]]

我如何生成这个数组或这个迭代器?

例如,对于 d=3 和 n=3,这将产生以下向量:

y[0]       : [x[0,0], x[1,0], x[2,0]]
y[1]       : [x[0,1], x[1,0], x[2,0]]
y[2]       : [x[0,2], x[1,0], x[2,0]]

y[3]       : [x[0,0], x[1,1], x[2,0]]
y[4]       : [x[0,1], x[1,1], x[2,0]]
y[5]       : [x[0,2], x[1,1], x[2,0]]

y[6]       : [x[0,0], x[1,2], x[2,0]]
y[7]       : [x[0,1], x[1,2], x[2,0]]
y[8]       : [x[0,2], x[1,2], x[2,0]]

y[9]       : [x[0,0], x[1,0], x[2,1]]
y[10]      : [x[0,1], x[1,0], x[2,1]]
y[11]      : [x[0,2], x[1,0], x[2,1]]

y[12]      : [x[0,0], x[1,1], x[2,1]]
y[13]      : [x[0,1], x[1,1], x[2,1]]
y[14]      : [x[0,2], x[1,1], x[2,1]]

y[15]      : [x[0,0], x[1,2], x[2,1]]
y[16]      : [x[0,1], x[1,2], x[2,1]]
y[17]      : [x[0,2], x[1,2], x[2,1]]

y[18]      : [x[0,0], x[1,0], x[2,2]]
y[19]      : [x[0,1], x[1,0], x[2,2]]
y[20]      : [x[0,2], x[1,0], x[2,2]]

y[21]      : [x[0,0], x[1,1], x[2,2]]
y[22]      : [x[0,1], x[1,1], x[2,2]]
y[23]      : [x[0,2], x[1,1], x[2,2]]

y[24]      : [x[0,0], x[1,2], x[2,2]]
y[25]      : [x[0,1], x[1,2], x[2,2]]
y[26]      : [x[0,2], x[1,2], x[2,2]]

我什至不知道应该有多少取决于 (n,d)...

你有什么想法吗?

可能有更简洁的方法来做到这一点,但我认为这可以满足要求。

import numpy as np

def rows( d, n ):
    """ Generates row indices. """
    arr = np.zeros( shape = d, dtype = np.int )

    def inc_row( arr ):
        for ix in range(0, len(arr)):
            arr[ ix ] += 1
            if arr[ ix ] < n:
                return arr   # If arr[ix] doesn't roll over return arr
            arr[ ix ] = 0      # Reset arr[ix] to zero if it rolls over
        return None   # Return None once all indices reset to zero. 

    while not arr is None:
        yield arr
        arr = inc_row( arr )

def permutations( base, d, n ):
    """ Generate the required combinations of values from base. """
    cols = np.arange( d )
    res = []
    for row in rows( d, n ):
        res.append( base[ row, cols ] )
    return np.array(res)

d = 3
n = 2

base = np.fromfunction( lambda x,y : x+y/10, shape = (n,d))
# For testing 'base' array values indicate location r.c

print(base)
# [[0.  0.1 0.2]
#  [1.  1.1 1.2]]

print(permutations( base, d, n ))
# [[0.  0.1 0.2]
#  [1.  0.1 0.2]
#  [0.  1.1 0.2]
#  [1.  1.1 0.2]
#  [0.  0.1 1.2]
#  [1.  0.1 1.2]
#  [0.  1.1 1.2]
#  [1.  1.1 1.2]]

HTH