user8591280
user8591280

Reputation: 69

How can I calculate matrix exponential in the fastest way in Python?

I would like to calculate the matrix exponential in Python. I found one way ("scipy.linalg.expm()"), but it takes long time (e.g. 30[sec] for 5000×5000 matrix).

matrix_exponential = scipy.linalg.expm(matrix)

Is there any faster way to calculate matrix exponential in Python?

Thank you very much in advance.

Upvotes: 2

Views: 5696

Answers (1)

qiushigu
qiushigu

Reputation: 21

Not sure if this is too late and I hope you have found out the answer.

I was facing the same issue while trying to solve the Stochastic Liouville equation in physics with large matrix sizes. It seems to me that the scipy implementation running on CPU is the fastest method.

There are two readily available packages I have found so far. One is the scipy linalg library (scipy.linalg.expm(A)) and the other is tensorflow linalg library (tf.linalg.expm(A)). Tensorflow will use GPUs to compute if appropriate cuda libraries have been installed. Both libraries can be incorporated without drastically changing the code structure. The tensorflow package requires converting between numpy arrays and tensorflow arrays. These operations involve copying data between system RAM and GPU memory that tend to be expensive.

For square matrix with size below 12393, it took the same time to run expm() function for both packages, but the tensorflow code took a lot longer IO time when converting between numpy and tf arrays and is overall slower.

CuPy also provides GPU computation capacity, however there is no readily available methods to run matrix exponentiation. Matrix inversion is also faster running on CPU with numpy compared to on GPU with cupy.

The above tests were run on a linux machine with Intel® Core™ i5-9400F CPU @ 2.90GHz × 6 and GeForce GTX 1050 Ti/PCIe/SSE2, using sparse matrix with sizes between 243 and 12393, based on 128-bit numpy complex numbers. Exponentiation of a 5000x5000 square matrix (64-bit float) takes 22 seconds on 6 cores, using scipy.linalg.expm(A).

Upvotes: 2

Related Questions