首頁  >  文章  >  後端開發  >  如何使用低維數組有效存取多維數組中的值?

如何使用低維數組有效存取多維數組中的值?

Barbara Streisand
Barbara Streisand原創
2024-10-21 13:34:02286瀏覽

How to Access Values in Multidimensional Arrays Using Lower- Dimensional Arrays Effectively?

使用低維數組存取多維數組

在多維數組中,使用較低維度的數組沿特定維度檢索值可以是具有挑戰性的。考慮下面的範例:

<code class="python">a = np.random.random_sample((3,4,4))
b = np.random.random_sample((3,4,4))
idx = np.argmax(a, axis=0)</code>

我們如何使用 idx 來存取 a 中的最大值,就像使用 a.max(axis=0) 一樣?我們如何從 b 檢索對應的值?

使用高級索引的優雅解決方案

高級索引提供了一種靈活的方法來實現此目的:

<code class="python">m, n = a.shape[1:]  # Extract dimensions excluding axis 0
I, J = np.ogrid[:m, :n]
a_max_values = a[idx, I, J]  # Index using the grid
b_max_values = b[idx, I, J]</code>

解決方案利用了網格[idx, I, J] 跨越剩餘維度的所有可能的索引組合的事實。

任意維度的泛化

對於一般的n維數組,可以定義一個函數來推廣上述解:

<code class="python">def argmax_to_max(arr, argmax, axis):
    """
    Apply argmax() operation along one axis to retrieve maxima.

    Args:
        arr: Array to apply argmax to
        argmax: Resulting argmax array
        axis: Axis to apply argmax (0-based)
    Returns:
        Maximum values along specified axis
    """
    new_shape = list(arr.shape)
    del new_shape[axis]

    grid = np.ogrid[tuple(map(slice, new_shape))]  # Create grid of indices
    grid.insert(axis, argmax)

    return arr[tuple(grid)]</code>

替代索引方法

或者,可以建立一個函數為所有軸產生索引網格:

<code class="python">def all_idx(idx, axis):
    grid = np.ogrid[tuple(map(slice, idx.shape))]
    grid.insert(axis, idx)
    return tuple(grid)</code>

然後可以使用該網格來存取具有較低維度數組的多維數組:

<code class="python">a_max_values = a[all_idx(idx, axis=axis)]
b_max_values = b[all_idx(idx, axis=axis)]</code>

以上是如何使用低維數組有效存取多維數組中的值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn