python - 有没有比在 python 中标记矩阵(3D 数组)的 for 循环更快的方法?

标签 python arrays performance numpy matrix

我用 Python 写了一个标记矩阵(3D 数组)的代码。 代码的概念是

  1. 检查 3D 数组中的 2 x 2 x 2 矩阵(无论我想要什么大小)
  2. 如果矩阵的元素为1、2、3,则矩阵中的所有元素都将变为矩阵中的“最大唯一数+1”。

    import numpy as np
    
    def label_A(input_field):
    labeling_A = np.copy(input_field)
    labeling_test = np.zeros((input_field.shape))
    for i in range(0,input_field.shape[0]-1):
        for j in range(0,input_field.shape[1]-1):
            for k in range(0,input_field.shape[2]-1):
                test_unit = input_field[i:i+2,j:j+2,k:k+2]
                if set(np.unique(test_unit).astype(int)) >= set((1,2,3)):
                    labeling_test[i:i+2,j:j+2,k:k+2] = np.max(input_field)+1
                    labeling_A[labeling_test == np.max(input_field)+1] = np.max(input_field)+1
        return labeling_A
    

这是一个简单的 3D 矩阵示例代码。

example = np.random.randint(0, 10, size=(10, 10, 10))
label_example = label_A(example)
label_example

在我看来,代码本身没有问题,而且确实有效。但是,我很好奇是否有更快的方法为此执行相同的功能?

最佳答案

此实现返回建议的结果并在 1.8 秒内处理 (140,140,​​140) 大小的张量。

import numpy as np
from scipy.signal import convolve

def strange_convolve(mat, f_shape, _value_set, replace_value):
    _filter =np.ones(tuple(s*2-1 for s in f_shape))
    replace_mat = np.ones(mat.shape)
    for value in _value_set:
        value_counts = convolve((mat==value),_filter,mode='same')
        replace_mat*=(value_counts>0)
    mat[replace_mat==1]=replace_value
    return mat
example = np.random.randint(0, 8, size=(10, 10, 10))
print('same_output validation is '+str((strange_convolve(example,(2,2,2),(1,2,3),4) == label_A(example)).min()))

import time 
example = np.random.randint(0, 10, size=(140, 140, 140))
timer = time.time()
strange_convolve(example,(2,2,2),(1,2,3),4)
print(time.time()-timer)

1.8871610164642334

关于python - 有没有比在 python 中标记矩阵(3D 数组)的 for 循环更快的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55051473/

相关文章:

python - 如何使用 web3py 的过滤器来获取智能合约的事件日志?

python - 是否可以从 nose 插件访问类级属性?

在 C 中将 void* 从短数组 (short*) 转换为 float 数组 (float)

javascript - Lodash 或将两个对象数组与匹配键组合的最佳方法

performance - 什么更有效率 : several insert vs single insert with union

python - 为什么这个 "[::-1]"在 Python 中返回一个反向列表?

python - 如何将 Quandl json 转换为 Python 字典?

python - 如何使用 numpy 查找 2D 和 3D 数组之间的并集?

xml - 大型 XML 包和使用属性或元素

c - 读取配置文件