我有一个布尔矩阵,它有1.5E6
行和20E3
列,类似于这个例子:
M = [[ True, True, False, True, ...],
[False, True, True, True, ...],
[False, False, False, False, ...],
[False, True, False, False, ...],
...
[ True, True, False, False, ...]
]
此外,我还有另一个矩阵N
(1.5E6
行,1
列):
N = [[ True],
[False],
[ True],
[ True],
...
[ True]
]
我需要做的是,逐列对矩阵
M
的每对列(1&1、1&2、1&3、1&N、2&1、2&2 等)进行 AND
运算,并计算结果与矩阵 N
之间有多少重叠。我的 Python/Numpy 代码如下:
for i in range(M.shape[1]):
for j in range(M.shape[1]):
result = M[:,i] & M[:,j] # Combine the columns with AND operator
count = np.sum(result & N.ravel()) # Counts the True occurrences
... # Save the count for the i and j pair
问题在于,使用两个for循环对20E3 x 20E3组合进行遍历计算速度非常慢(需要5-10天的时间来计算)。我尝试了一种更好的方法,那就是将每列与整个矩阵M进行比较:
for i in range(M.shape[1]):
result = M[:,i]*M.shape[1] & M # np.tile or np.repeat is used to horizontally repeat the column
counts = np.sum(result & N*M.shape[1], axis=0)
... # Save the counts
这将减少开销和计算时间约为10%,但仍需要大约1天的时间来计算。 我的问题是:有没有更快的方法(也许不是Python)来进行这些计算(基本上只是AND和SUM)? 我在考虑低级语言、GPU处理、量子计算等等,但我对这些都不太了解,所以欢迎任何关于方向的建议! 其他想法: 目前在思考是否有使用点积的快速方法来计算组合的三元组(如Davikar提出的)。
def compute(M, N):
out = np.zeros((M.shape[1], M.shape[1], M.shape[1]), np.int32)
for i in range(M.shape[1]):
for j in range(M.shape[1]):
for k in range(M.shape[1]):
result = M[:, i] & M[:, j] & M[:, k]
out[i, j, k] = np.sum(result & N.ravel())
return out
tensorflow
标签的原因?当您说“1.5mm”时,是指150万行吗?只是为了澄清。此外,您对count
做什么?您是累加总和,还是每个count
存储在单独的位置,或者其他什么操作? - jdehesa