【问题标题】:Reshaping numpy array to be similar to different array with arbitrarily nested subarrays将numpy数组重塑为类似于具有任意嵌套子数组的不同数组
【发布时间】:2021-03-10 13:42:29
【问题描述】:

我有两个数组 ab。如果我运行a.shape,我得到(10,),如果我运行(b.shape),我得到(10,),但是这些值中的每一个都是任意嵌套的数组,它们的形状与其他数组本身或与其他数组。例如 a[0].shape 返回 (122,)b[0].shape 返回 (3900,)b[5].shape 返回 (5200,64) 所以它们在同一个数组中甚至不一致。

我知道使用Iterating through a multidimensional array in Python 的递归解决方案它们的元素总数相同(似乎没有标准的 numpy 函数能够根据需要深入到数组中):

def iterThrough(lists):
  if not hasattr(lists[0], '__iter__'):
    for val in lists:
      yield val
  else:
    for l in lists:
      for val in iterThrough(l):
        yield val
            si = 0

for value in iterThrough(a): #and b
    si += 1

两者都返回3066752。我知道这很混乱,但我需要它处于那种形状以便稍后计算数学函数,我猜这样做比重写该方程以反映格式良好的数组更容易。

如何使数组a 的所有嵌套形状与数组b 完全相同?

【问题讨论】:

  • 如果你有这些奇怪的数据,我不明白你为什么要使用 Numpy 或者你希望从中获得什么好处。无论如何,您提出的问题毫无意义:您实际上想对这些值做什么?什么规则告诉您原始数组中的任何给定元素应该在重构后的数组中的位置?
  • 我不明白你在问什么,如果你“需要它是那种形状”但想要两个数组“完全相同”。你能发布一个预期的输出和当前的形状
  • @Kenan 它不需要(我也不希望它)内容相同,只是形状应该相同。我正在想象类似 pytorch view pytorch.org/docs/stable/tensors.html#torch.Tensor.view 的函数,它允许我将其制作成任何我想要的形状,但这些类型的函数似乎不适用于 Numpy 中的这个数组。

标签: python arrays numpy


【解决方案1】:

这是一个可以完成这项工作的解决方案,但保证速度很慢,因为它是递归的、迭代的,并且根本不向量化:

import copy

# Generator function:
# Returns successive scalars from any crazily nested array
def arr_values(arr):
    for elem in arr:
        if (isinstance(elem, np.ndarray)):
            for sub_arr_elem in arr_values(elem):
                yield sub_arr_elem
        else:
            yield elem

# Generator function:
# Returns successive tuples (vector, index) from any arbitrarily nested array,
# such that assigning a value to vector[index] is the same as assigning the value
# to a position in the input array.
def arr_positions(arr):
    for pos,elem in enumerate(arr):
        if (isinstance(elem, np.ndarray)):
            for inner_arr_pos in arr_positions(elem):
                yield inner_arr_pos
        else:
            yield arr, pos

# Create a new array, having the shape of `b` (and incidentally, b's data also)
arr_in_shape_of_b = copy.deepcopy (b)

# Get the iterator for successive assignable positions in
# our destination array
iter_dest = arr_positions(arr_in_shape_of_b)

# Get the iterator for successive scalars from our source array
iter_src = arr_values(a)

# Now, iterate over the two iterators in tandem, and
# perform assignment of successive values from source,
# into successive positions in destination.
for ((dest_vec, pos), val) in zip(iter_dest, iter_src):
    dest_vec[pos] = val

测试一下:

我使用ab 的演示数据进行了测试:

a = np.array ([np.arange(6).reshape(2,3), np.array([np.arange(8).astype(np.ndarray),
                                                    23], dtype=np.ndarray),24], dtype=np.ndarray)
print (a.shape)
print (a)

b = np.roll(-1 * a, 2, axis=0)
print (b.shape)
print (b)

所以,输入数组 ab 如下所示:

(3,)
[array([[0, 1, 2],
       [3, 4, 5]])
 array([array([0, 1, 2, 3, 4, 5, 6, 7], dtype=object), 23], dtype=object)
 24]
(3,)
[array([array([0, -1, -2, -3, -4, -5, -6, -7], dtype=object), -23],
      dtype=object)
 -24 array([[ 0, -1, -2],
       [-3, -4, -5]])]

输出如下所示:

(3,)
[array([array([0, 1, 2, 3, 4, 5, 0, 1], dtype=object), 2], dtype=object) 3
 array([[ 4,  5,  6],
       [ 7, 23, 24]])]

【讨论】:

    猜你喜欢
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 2017-09-18
    • 2020-04-22
    • 1970-01-01
    • 2020-03-18
    相关资源
    最近更新 更多