我正在研究一个用Keras和Tensorflow实现的强化学习模型。我经常打电话给模型.预测()单输入。在
在一个简单的预训练模型上测试推理时,我注意到使用Keras'模型.预测比在存储的权重上使用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
memory leak issue似乎仍然存在于Keras中。那期文章中提到的以下几行代码对我起了作用:
您是否在循环中运行Keras模型(使用TensorFlow后端)?如果是这样的话,Keras在这里发现了内存泄漏问题:LINK
在这种情况下,您必须导入以下内容:
最后,在完成计算后,必须在循环的每次迭代结束时放置以下内容:
^{pr2}$这将有助于您在每个循环结束时释放内存,并最终使该过程更快。我希望这有帮助。在
有点晚,但可能对某人有用:
将
model.predict(X)
替换为model.predict(X, batch_size=len(X))
那应该行了。在
相关问题 更多 >
编程相关推荐