gpt4 book ai didi

python - 设置 csr_matrix 的行

转载 作者:太空宇宙 更新时间:2023-11-03 14:20:39 25 4
gpt4 key购买 nike

我有一个稀疏的 csr_matrix,我想将单行的值更改为不同的值。但是,我找不到简单有效的实现方式。这是它必须做的:

A = csr_matrix([[0, 1, 0],
[1, 0, 1],
[0, 1, 0]])
new_row = np.array([-1, -1, -1])
print(set_row_csr(A, 2, new_row).todense())

>>> [[ 0, 1, 0],
[ 1, 0, 1],
[-1, -1, -1]]

这是我目前对 set_row_csr 的实现:

def set_row_csr(A, row_idx, new_row):
A[row_idx, :] = new_row
return A

但这给了我一个 SparseEfficiencyWarning。有没有一种方法可以在不手动索引杂耍的情况下完成这项工作,或者这是我唯一的出路?

最佳答案

physicalattraction 的回答确实要快得多。它比我的解决方案快得多,我的解决方案只是添加一个单独的矩阵与该单行集。虽然添加解决方案比切片解决方案更快。

对我来说,在 csr_matrix 中设置行或在 csc_matrix 中设置列​​的最快方法是自己修改基础数据。

def time_copy(A, num_tries = 10000):
start = time.time()
for i in range(num_tries):
B = A.copy()
end = time.time()
return end - start

def test_method(func, A, row_idx, new_row, num_tries = 10000):
start = time.time()
for i in range(num_tries):
func(A.copy(), row_idx, new_row)
end = time.time()
copy_time = time_copy(A, num_tries)
print("Duration {}".format((end - start) - copy_time))

def set_row_csr_slice(A, row_idx, new_row):
A[row_idx,:] = new_row

def set_row_csr_addition(A, row_idx, new_row):
indptr = np.zeros(A.shape[1] + 1)
indptr[row_idx +1:] = A.shape[1]
indices = np.arange(A.shape[1])
A += csr_matrix((new_row, indices, indptr), shape=A.shape)

>>> A = csr_matrix((np.ones(1000), (np.random.randint(0,1000,1000), np.random.randint(0, 1000, 1000))))
>>> test_method(set_row_csr_slice, A, 200, np.ones(A.shape[1]), num_tries = 10000)
Duration 4.938395977020264

>>> test_method(set_row_csr_addition, A, 200, np.ones(A.shape[1]), num_tries = 10000)
Duration 2.4161765575408936

>>> test_method(set_row_csr, A, 200, np.ones(A.shape[1]), num_tries = 10000)
Duration 0.8432261943817139

随着矩阵的大小和稀疏性,切片解决方案的缩放比例也更差。

# Larger matrix, same fraction sparsity
>>> A = csr_matrix((np.ones(10000), (np.random.randint(0,10000,10000), np.random.randint(0, 10000, 10000))))
>>> test_method(set_row_csr_slice, A, 200, np.ones(A.shape[1]), num_tries = 10000)
Duration 18.335174798965454

>>> test_method(set_row_csr, A, 200, np.ones(A.shape[1]), num_tries = 10000)
Duration 1.1089558601379395

# Super sparse matrix
>>> A = csr_matrix((np.ones(100), (np.random.randint(0,10000,100), np.random.randint(0, 10000, 100))))
>>> test_method(set_row_csr_slice, A, 200, np.ones(A.shape[1]), num_tries = 10000)
Duration 13.371600151062012

>>> test_method(set_row_csr, A, 200, np.ones(A.shape[1]), num_tries = 10000)
Duration 1.0454308986663818

关于python - 设置 csr_matrix 的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28427236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com