簡體   English   中英

tf.keras.predict() 比 Keras predict() 慢得多

[英]tf.keras.predict() is much slower than Keras predict()

When using the Keras that comes embedded with Tensorflow (Tensorflow 2), I noticed a severe increase in computational time when using the predict() function from the Keras embedded inside Tensorflow and the predict() from standalone Keras. 請參閱下面的玩具代碼:

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)

我機器下面代碼中的 output 是

17.82757878303528
0.31248927116394043

The expected output is that the predict() from tensorflow.keras should take the same amount of time for the same task, when compared to the predict() from standalone Keras.

我的問題是:

  1. 為什么會這樣?
  2. 我怎樣才能解決這個問題?

我的規格:

Python 版本:Python 3.6.8

Keras 版本:2.3.1

Tensorflow 版本:2.1.0

在 Windows 10 上運行

這主要是由於急切的執行。 您可以關閉急切執行

tensorflow.compat.v1.disable_eager_execution()

這樣做,tf.keras 仍然慢了約 2 倍,我不知道為什么,但不是數量級。 如果您事先轉換為張量,它們 go 會更快。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM