Sea*_*ice 5 python eigenvalue eigenvector tensorflow
我在 Tensorflow 中使用特征分解,发现它非常慢。下面的代码显示了 Tensorflow 的速度与 numpy 和 scipy 的比较:
import numpy as np
import scipy as sp
import tensorflow as tf
from time import time
A = np.random.randn(400, 400)
A_tf = tf.constant(A)
cur = time()
d, v = sp.linalg.eig(A)
print(f'sp: {time() - cur:4.2f} s')
cur = time()
d, v = np.linalg.eig(A)
print(f'np: {time() - cur:4.2f} s')
cur = time()
d, v = tf.linalg.eig(A_tf)
print(f'tf: {time() - cur:4.2f} s')
Run Code Online (Sandbox Code Playgroud)
这给出了以下输出:
sp: 0.09 s
np: 0.08 s
tf: 5.04 s
Run Code Online (Sandbox Code Playgroud)
对这里有什么想法吗?
小智 1
尝试tf.linalg.eig用 a 包裹起来@tf.function,您可以观察到速度的提高。这是因为它转换为图形模式,并且可以进行一些优化。
在 Eager 模式下,这些可能不会执行,这是 TF 2.x 中的默认行为。
您可以如下所示包装您的代码
@tf.function
def oper(A_tf):
d, v = tf.linalg.eig(A_tf)
Run Code Online (Sandbox Code Playgroud)
请参考下面的速度比较
import numpy as np
import scipy as sp
import tensorflow as tf
from time import time
A = np.random.randn(400, 400)
A_tf = tf.constant(A)
cur = time()
d, v = sp.linalg.eig(A)
print(f'sp: {time() - cur:4.2f} s')
cur = time()
d, v = np.linalg.eigh(A)
print(f'np: {time() - cur:4.2f} s')
d, v = tf.linalg.eig(A_tf)
print(f'tf: {time() - cur:4.2f} s')
@tf.function
def oper(A_tf):
cur = time()
d, v = tf.linalg.eig(A_tf)
print(f'tff: {time() - cur:4.2f} s')
oper(A_tf)
Run Code Online (Sandbox Code Playgroud)
输出:
sp: 0.32 s
np: 0.04 s
tf: 3.62 s
tff: 0.01 s
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅@tf.function,查看速度提升以及我应该对所有函数使用 @tf.function 吗?今天之前。
| 归档时间: |
|
| 查看次数: |
565 次 |
| 最近记录: |