如何递归放大 Numpy 数组

How to Zoom in Recursively on a Numpy Array

我试图证明我生成的数组在多个长度尺度上看起来自相似。为此,我想编写一个函数来打印输入数组的左上角,然后打印该部分的左上角,依此类推指定的迭代次数。我写了这个递归函数。但是,输出不是我所期望的。

def zoom(array, max_zoom, zoom_level):
    half_width = int(array.shape[0]/2)
    half_height = int(array.shape[1]/2)
    print(array)

    while zoom_level < max_zoom:
        array = array[:half_width, :half_height]
        zoom_level += 1
        zoom(array, max_zoom, zoom_level)

问题不是打印到所需的级别然后停止,而是数组开始再次变大并且函数在几次额外的迭代后停止。

例如 zoom(array, 3, 0) 应该给出以下 8x8 网格的输出。

[[0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0.]] 

[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]

[[0. 0.]
[0. 0.]]

[[0.]]

而是给出:

[[0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]
[[0. 0.]
 [0. 0.]]
[[0.]]
[[0. 0.]
 [0. 0.]]
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]
[[0. 0.]
 [0. 0.]]
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]

任何人都可以解释为什么这个函数运行不正常吗?

问题是你的递归函数有一段时间了。您正在做的是对每个递归调用重复相同的过程,从而打印不必要的结果。

def zoom(array, max_zoom, zoom_level):
    print(array)
    if zoom_level < max_zoom:
        half_width = array.shape[0] // 2
        half_height = array.shape[1] // 2
        array = array[:half_width, :half_height]
        zoom_level += 1
        zoom(array, max_zoom, zoom_level)

A = np.zeros((9, 9))

zoom(A, 3, 0)

输出将是:

[[0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]
[[0. 0.]
 [0. 0.]]
[[0.]]