这里有一个可能对您有用的快速技巧。 (这是一个 hack,因为它覆盖了一个没有真正记录为公共 API 一部分的类的私有静态方法。如果在 SciPy 的未来版本中更改了底层代码,这个 hack 可能不再起作用。)
创建scipy.io.mmfile.MMFile 的子类,覆盖_field_template 方法,以便返回自定义格式字符串。例如
from scipy.io.mmio import MMFile
class MMFileFixedFormat(MMFile):
def _field_template(self, field, precision):
# Override MMFile._field_template.
return f'%.{precision}f\n'
要使用此类编写矩阵市场文件,请将您对函数 scipy.io.mmwrite 的使用替换为 MMFileFixedFormat().write。
这是一个 ipython 会话中的示例。稀疏矩阵在a。
In [77]: a
Out[77]:
<5x5 sparse matrix of type '<class 'numpy.float32'>'
with 8 stored elements in Compressed Sparse Row format>
In [78]: a.A
Out[78]:
array([[0.27621606, 0. , 0. , 0.7780487 , 0. ],
[0.7295764 , 0. , 0. , 0. , 0. ],
[0.09457383, 0. , 0.13346413, 0. , 0. ],
[0. , 0. , 0.11267778, 0. , 0. ],
[0.05113978, 0. , 0. , 0.9891698 , 0. ]],
dtype=float32)
这是将a 写入文件"a.mtx" 的行。
In [79]: MMFileFixedFormat().write('a.mtx', a, precision=9)
看一下文件:
In [80]: !cat a.mtx
%%MatrixMarket matrix coordinate real general
%
5 5 8
1 1 0.27621606
1 4 0.77804869
2 1 0.72957641
3 1 0.09457383
3 3 0.13346413
4 3 0.11267778
5 1 0.05113978
5 4 0.98916978
您可能想要调整在函数_field_template() 中创建的格式字符串。具有固定小数位数的格式的一个潜在问题是,如果条目的值为0.00000098765432,它将打印为0.000000099,而0.0000000000123 将打印为0.00000000(假设您使用与上例中的precision 相同)。
但请注意,矩阵市场文件的适当阅读器应该能够处理以科学记数法书写的数字。