Sparse × Sparse matrix product 只计算它的一些元素
Sparse × Sparse matrix product which computes only some its elements
假设A
、B
和C
是任意格式的稀疏矩阵。我想知道如何仅针对 C
.
中的非零元素有效地计算它们的点积
等于
prod = A.dot(B)
prod[C == 0] = 0
对于 Python 中的密集矩阵。但是这段代码效率极低。
你能给我一些建议吗?内存无所谓。
您可以将 C
转换为布尔值,并利用值 True
在乘法上下文中将变为 1
的事实。然后,您可以在 A.dot(B)
和 C
.
的乘积之间进行逐元素乘法
您可以通过以下方式实现:
A.dot(B).to_csr().multiple(C.to_csr())
更快的点积
为了获得尽可能快的点积,我将对 scipy
提供的所有稀疏格式进行暴力搜索。定义一个计时函数如:
from functools import wraps
from time import time
def timing(f):
@wraps(f)
def wrapper(*args, **kwargs):
start = time()
result = f(*args, **kwargs)
end = time()
print 'Elapsed time: {}'.format(end-start)
return result
return wrapper
@timing
def csr_dot(a, b):
# Write similar functions for all other formats
return a.to_csr().dot(b.to_csr())
# This will print some time. Repeat for other formats.
csr_dot(A, B)
然后您可以选择产生最佳时间的格式。
假设A
、B
和C
是任意格式的稀疏矩阵。我想知道如何仅针对 C
.
等于
prod = A.dot(B)
prod[C == 0] = 0
对于 Python 中的密集矩阵。但是这段代码效率极低。
你能给我一些建议吗?内存无所谓。
您可以将 C
转换为布尔值,并利用值 True
在乘法上下文中将变为 1
的事实。然后,您可以在 A.dot(B)
和 C
.
您可以通过以下方式实现:
A.dot(B).to_csr().multiple(C.to_csr())
更快的点积
为了获得尽可能快的点积,我将对 scipy
提供的所有稀疏格式进行暴力搜索。定义一个计时函数如:
from functools import wraps
from time import time
def timing(f):
@wraps(f)
def wrapper(*args, **kwargs):
start = time()
result = f(*args, **kwargs)
end = time()
print 'Elapsed time: {}'.format(end-start)
return result
return wrapper
@timing
def csr_dot(a, b):
# Write similar functions for all other formats
return a.to_csr().dot(b.to_csr())
# This will print some time. Repeat for other formats.
csr_dot(A, B)
然后您可以选择产生最佳时间的格式。