在矩阵中计算邻居 - 康威生命游戏

5

对于每个矩阵元素,我想要加上它周围所有单元格的值。

从我的初始数组开始:

board = np.array([[0, 1, 1],
                   [0, 1, 0],
                   [1, 0, 0]])

我的结果应该是:

([2,2,2],
 [3,3,3],
 [1,2,1])

我创建了一个函数,并使用了暴力方法来查找单元格是否存在于周围。如果存在,则将其值相加并返回总和。我不确定我的 if 语句是否正确。它显示以下错误:
“数组的真值在有多个元素时是模糊的:请使用 a.any() 或 a.all()”。
def count_living_neighbors(board):
    count = np.zeros(board.shape, dtype=int)
    #
    # YOUR CODE HERE
    #

    for row in range(len(board)):
        for column in range(len(board[row])):
            total = 0
            if (board[column - 1]).any() in board:
                total += board[row][column-1]
            if (board[column + 1]).any() in board:
                total += board[row][column+1]    
            if (board[row - 1]).any() in board:
                total += board[row-1][column]
            if (board[row + 1]).any() in board:
                total += board[row+1][column]
            if (board[row + 1] and board[column - 1]).any() in board:
                total += board[row+1][column-1]
            if (board[row - 1] and board[column - 1]).any() in board:
                total += board[row-1][column-1]
            if (board[row + 1] and board[column + 1]).any() in board:
                total += board[row+1][column+1]
            if (board[row - 1] and board[column + 1]).any() in board:
                total += board[row+1][column+1]

            count[row][column] = total         

    return count

听起来像是使用卷积核进行卷积。可以查看scipy相关文档了解更多信息。 - Magellan88
你遇到的特定错误是因为你使用了错误的 and。请尝试使用 &。但我认为还有几个额外的错误。 - Paul Panzer
3个回答

5
你可以使用 scipy.signal.convolve 函数,并设置参数 mode='same' 来进行卷积操作:
from scipy import signal

kernel = np.ones((3, 3), dtype=np.int8)
kernel[1, 1] = 0
print(signal.convolve(board, kernel, mode='same'))
[[2 2 2]
 [3 3 3]
 [1 2 1]]

这里的内核长这样:

array([[1, 1, 1],
       [1, 0, 1],
       [1, 1, 1]], dtype=int8)

无论 board 的形状如何,kernel 都将保持不变。基本上,kernel 是指邻居的位置(相对于中心的 0)。


-1
尝试使用scipy.signal.convolve2d函数,类似于这样。
convolve2d( yourMatrix, np.ones((3,3))

应该可以解决问题


-1
关于你的代码: 你可能对Python或numpy语法不是很熟悉,所以我建议找一些教程来练习基础知识。 (board[column - 1]).any()如果整个列中有任何一个单元格是活着的,则为True,否则为False。之后,您正在测试是否包含在始终为True的板子中的True(或False,如果列中所有单元格都死亡)。因此,您的if语句没有太多意义。
为了测试邻居中的一个单元格是否存活,它看起来像以下任何一个if语句:
if board[row-1][column - 1]  ==  1:
if board[row-1, column - 1]   ==  1: 
if board[row-1, column - 1] : #in Python 1 is True and 0 is False

话虽如此,要计算一个点周围有多少个存活的细胞,你根本不需要使用if语句,只需将所有周围的值相加,死亡的细胞值为0,而活着的细胞值为1,因此只有活着的细胞才会在计数中出现。 而且,如果你的代码进一步发展,它将非常缓慢,你永远不应该使用for循环来迭代numpy数组,正确的做法是利用所谓的向量化操作,即一次对整个数组进行操作的操作,例如:board[:,1:]+board[:,:-1]将为您提供一个包含左侧单元格+右侧单元格之和的数组,其中您可以计算该总和的每个单元格。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接