我有两个变量r
和e
这两个变量都是字典,字符串作为键和csr_matrices作为值。现在我想断言他们是平等的。我该怎么做呢?Python比较字典与csr_matrices作为值
尝试1:
from scipy.sparse.csr import csr_matrix
import numpy as np
def test_dict_equals(self):
r = {'a': csr_matrix([[0, 0 ,1], [0, 1, 0], [1, 0, 0]])}
e = {'a': csr_matrix([[0, 0 ,1], [0, 1, 0], [1, 0, 0]])}
self.assertDictEqual(r, e)
这不起作用:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().
尝试2:
def test_dict_equals(self):
r = {'a': csr_matrix([[0, 0 ,1.01], [0, 1, 0], [1, 0, 0]])}
e = {'a': csr_matrix([[0, 0 ,1.01], [0, 1, 0], [1, 0, 0]])}
self.assertListEqual(r.keys(), e.keys())
for k in r.keys():
np.testing.assert_allclose(r[k], e[k])
但这也不起作用:
AssertionError: First sequence is not a list: dict_keys(['a'])
尝试3:
def test_dict_equals(self):
r = {'a': csr_matrix([[0, 0 ,1.01], [0, 1, 0], [1, 0, 0]])}
e = {'a': csr_matrix([[0, 0 ,1.01], [0, 1, 0], [1, 0, 0]])}
self.assertListEqual(list(r.keys()), list(e.keys()))
for k in r.keys():
np.testing.assert_allclose(r[k], e[k])
但这也不起作用:
TypeError: ufunc 'isinf' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
谢谢。我确实现在正在测试A.data,A.indices和A.indptr。您引用的测试目录是用于执行csr_matrix的测试代码,而不是用于测试的帮助函数。 – physicalattraction
注意:有可能有两个相同的矩阵,但具有不同的indptr/indices/data数组。这两个非零元素的顺序不同。这导致错误检测到不平等。 – physicalattraction