tf.keras.predict() 比 Keras predict() 慢得多
tf.keras.predict() is much slower than Keras predict()
当使用嵌入 Tensorflow (Tensorflow 2) 的 Keras 时,我注意到使用嵌入在 Tensorflow 中的 Keras 的 predict()
函数和来自独立的凯拉斯。请参阅下面的玩具代码:
import tensorflow
import keras
import numpy as np
import time
test = np.array([[0.1, 0.1, 0.1, 0.1, 0.1, 0.5, 0.1, 0., 0.1, 0.2]])
# Keras from inside Tensorflow
model_1 = tensorflow.keras.Sequential([
tensorflow.keras.layers.Dense(1, activation='relu', input_shape=(10,)),
])
start_1 = time.time()
for i in range(1000):
result = model_1.predict(test)
elapsed_time_1 = time.time() - start_1
# Standalone Keras
model_2 = keras.models.Sequential([
keras.layers.Dense(1, activation='relu', input_shape=(10,)),
])
start_2 = time.time()
for i in range(1000):
result = model_2.predict(test)
elapsed_time_2 = time.time() - start_2
print(elapsed_time_1)
print(elapsed_time_2)
下面代码在我机器上的输出是
17.82757878303528
0.31248927116394043
预期输出是 tensorflow.keras
的 predict()
与独立 Keras 的 predict()
相比,相同的任务应该花费相同的时间。
我的问题是:
- 为什么会这样?
- 我该如何解决这个问题?
我的规格:
Python version: Python 3.6.8
Keras version: 2.3.1
Tensorflow version: 2.1.0
Running on Windows 10
这主要是由于急于执行。您可以使用
关闭急切执行
tensorflow.compat.v1.disable_eager_execution()
这样做,tf.keras 仍然慢了约 2 倍,我不确定为什么,但不是数量级。如果你事先转换为张量,它们都运行得更快。
当使用嵌入 Tensorflow (Tensorflow 2) 的 Keras 时,我注意到使用嵌入在 Tensorflow 中的 Keras 的 predict()
函数和来自独立的凯拉斯。请参阅下面的玩具代码:
import tensorflow
import keras
import numpy as np
import time
test = np.array([[0.1, 0.1, 0.1, 0.1, 0.1, 0.5, 0.1, 0., 0.1, 0.2]])
# Keras from inside Tensorflow
model_1 = tensorflow.keras.Sequential([
tensorflow.keras.layers.Dense(1, activation='relu', input_shape=(10,)),
])
start_1 = time.time()
for i in range(1000):
result = model_1.predict(test)
elapsed_time_1 = time.time() - start_1
# Standalone Keras
model_2 = keras.models.Sequential([
keras.layers.Dense(1, activation='relu', input_shape=(10,)),
])
start_2 = time.time()
for i in range(1000):
result = model_2.predict(test)
elapsed_time_2 = time.time() - start_2
print(elapsed_time_1)
print(elapsed_time_2)
下面代码在我机器上的输出是
17.82757878303528
0.31248927116394043
预期输出是 tensorflow.keras
的 predict()
与独立 Keras 的 predict()
相比,相同的任务应该花费相同的时间。
我的问题是:
- 为什么会这样?
- 我该如何解决这个问题?
我的规格:
Python version: Python 3.6.8
Keras version: 2.3.1
Tensorflow version: 2.1.0
Running on Windows 10
这主要是由于急于执行。您可以使用
关闭急切执行tensorflow.compat.v1.disable_eager_execution()
这样做,tf.keras 仍然慢了约 2 倍,我不确定为什么,但不是数量级。如果你事先转换为张量,它们都运行得更快。