给定一个 nxn 矩阵 A(它实际上是图的邻接矩阵),我需要查看该矩阵的所有可能的 mxm 子矩阵(在本例中为 m = 8),并将子矩阵传递给函数并收集其结果。
现在,我是这样做的:
# generate all possible 8x8 submatrices
for w in itertools.combinations(range(n), m):
# extract 8x8 submatrix from the matrix
submatrix = A[np.ix_(list(w),list(w))]
# do some work on the submatrix
foo(submatrix)
问题是:上面的代码适用于 n=30x30 矩阵(大约有 500 万个可能的 m=8x8 子矩阵要搜索)。但是,我想将我的算法应用于最多 n=100x100 个矩阵,这意味着(100 选择 8)= 1860 亿个可能的子矩阵。
有什么可以让我更快地完成这个过程?还是难以解决?
最佳答案
import numpy as np
from scipy.ndimage import generic_filter
m = np.arange(100*100).reshape((100,100))
def myfunction(data):
mean = np.mean(data)
return mean
%timeit results = generic_filter(m, myfunction, size=8)
#10 loops, best of 3: 96.6 ms per loop
使用 generic_filter 的解决方案scipy.ndimage 的
关于python - 如何在 Python 中高效地对大型矩阵执行网格搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21805827/