我正在研究使用 Keras 和 Tensorflow 实现的强化学习模型。我必须在单个输入上频繁调用 model.predict()。
在简单的预训练模型上测试推理时,我注意到使用 Keras 的 model.predict 比仅在存储的权重上使用 Numpy 慢得多。为什么这么慢,我怎样才能加速它?使用纯 Numpy 对于复杂模型来说是不可行的。
import timeit
import numpy as np
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dense
w = np.array([[-1., 1., 0., 0.], [0., 0., -1., 1.]]).T
b = np.array([ 15., -15., -21., 21.])
model = Sequential()
model.add(Dense(4, input_dim=2, activation='linear'))
model.layers[0].set_weights([w.T, b])
model.compile(loss='mse', optimizer='adam')
state = np.array([-23.5, 17.8])
def predict_very_slow():
return model.predict(state[np.newaxis])[0]
def predict_slow():
ws = model.layers[0].get_weights()
return np.matmul(ws[0].T, state) + ws[1]
def predict_fast():
return np.matmul(w, state) + b
print(
timeit.timeit(predict_very_slow, number=10000),
timeit.timeit(predict_slow, number=10000),
timeit.timeit(predict_fast, number=10000)
)
# 5.168972805004538 1.6963867129435828 0.021918574168087623
# 5.461319456664639 1.5491559107269515 0.021502970783442876
最佳答案
有点晚了,但可能对某人有用:
将 model.predict(X)
替换为 model.predict(X, batch_size=len(X))
应该可以了。
关于python - 为什么 TF Keras 推理比 Numpy 运算慢得多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48796619/