10

numpy.arrayNxM から NxMx3 にマップしたいのですが、3 つの要素のベクトルは元のエントリの関数です。

lambda x: [f1(x), f2(x), f3(x)]

ただし、次のようなものnumpy.vectorizeは寸法を変更できません。確かに、ゼロの配列を作成してループを作成することはできます (そして、それは私が今やっていることです)。

numpy.array で要素ごとの操作を実行し、各エントリのベクトルを生成するより良い方法はありますか?

4

2 に答える 2

4

コードを確認したので、ほとんどの単純な数学演算では、numpy にループを実行させることができます。これは、しばしばvectorizationと呼ばれます。

def complex_array_to_rgb(X, theme='dark', rmax=None):
    '''Takes an array of complex number and converts it to an array of [r, g, b],
    where phase gives hue and saturaton/value are given by the absolute value.
    Especially for use with imshow for complex plots.'''
    absmax = rmax or np.abs(X).max()
    Y = np.zeros(X.shape + (3,), dtype='float')
    Y[..., 0] = np.angle(X) / (2 * pi) % 1
    if theme == 'light':
        Y[..., 1] = np.clip(np.abs(X) / absmax, 0, 1)
        Y[..., 2] = 1
    elif theme == 'dark':
        Y[..., 1] = 1
        Y[..., 2] = np.clip(np.abs(X) / absmax, 0, 1)
    Y = matplotlib.colors.hsv_to_rgb(Y)
    return Y

このコードは、あなたのコードよりもはるかに高速に実行されるはずです。

于 2013-06-16T14:33:02.047 に答える
4

問題を正しく理解している場合は、次を使用することをお勧めしますnp.dstack

Docstring:
Stack arrays in sequence depth wise (along third axis).

Takes a sequence of arrays and stack them along the third axis
to make a single array. Rebuilds arrays divided by `dsplit`.
This is a simple way to stack 2D arrays (images) into a single
3D array for processing.

    In [1]: a = np.arange(9).reshape(3, 3)

    In [2]: a
    Out[2]: 
    array([[0, 1, 2],
           [3, 4, 5],
           [6, 7, 8]])

    In [3]: x, y, z = a*1, a*2, a*3  # in your case f1(a), f2(a), f3(a) 

    In [4]: np.dstack((x, y, z))
    Out[4]: 
    array([[[ 0,  0,  0],
            [ 1,  2,  3],
            [ 2,  4,  6]],

           [[ 3,  6,  9],
            [ 4,  8, 12],
            [ 5, 10, 15]],

           [[ 6, 12, 18],
            [ 7, 14, 21],
            [ 8, 16, 24]]])
于 2013-06-15T12:45:19.493 に答える