Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Tensorflow特征值分解非常慢_Python_Tensorflow_Eigenvalue_Eigenvector - Fatal编程技术网

Python Tensorflow特征值分解非常慢

Python Tensorflow特征值分解非常慢,python,tensorflow,eigenvalue,eigenvector,Python,Tensorflow,Eigenvalue,Eigenvector,我在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:

我在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')
这将提供以下输出:

sp: 0.09 s
np: 0.08 s
tf: 5.04 s

有什么想法吗?

尝试在
@tf.function
中包装
tf.linalg.eig
,您可以观察到速度的提高。 这是因为它转换为图形模式,可以进行一些优化

在渴望模式的情况下,这些可能不会执行,这是TF2.x中的默认行为

您可以按如下所示包装代码

@tf.function
def oper(A_tf):
    d, v = tf.linalg.eig(A_tf)
请参考下面的比较w.r.t速度

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) 
输出:

sp: 0.32 s
np: 0.04 s
tf: 3.62 s
tff: 0.01 s

有关更多信息,请参阅,到今天。

要获得更好的性能,请尝试在
@tf.function
中包装
tf.linalg.eig
。有关更多详细信息,请参阅。谢谢