【发布时间】:2020-11-28 04:12:28
【问题描述】:
我正在尝试检查 Keras 模型不同层的执行速度(使用 tensorflow 2.3.0 v 中的 keras)
我从repo 获取代码并对其进行了修改,以使用来自from timeit import default_timer 的timer() 计算时间
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from timeit import default_timer as timer
def time_per_layer(model):
new_model = model
times = np.zeros((len(model.layers), 2))
inp = np.ones((70, 140, 1))
for i in range(1, len(model.layers)):
new_model = tf.keras.models.Model(inputs=[model.input], outputs=[model.layers[-i].output])
# new_model.summary()
new_model.predict(inp[None, :, :, :])
t_s = timer()
new_model.predict(inp[None, :, :, :])
t_e2 = timer() - t_s
times[i, 1] = t_e2
del new_model
for i in range(0, len(model.layers) - 1):
times[i, 0] = abs(times[i + 1, 1] - times[i, 1])
times[-1, 0] = times[-1, 1]
return times
times = time_per_layer(model)
plt.style.use('ggplot')
x = [model.layers[-i].name for i in range(1,len(model.layers))]
#x = [i for i in range(1,len(model.layers))]
g = [times[i,0] for i in range(1,len(times))]
x_pos = np.arange(len(x))
plt.bar(x, g, color='#7ed6df')
plt.xlabel("Layers")
plt.ylabel("Processing Time")
plt.title("Processing Time of each Layer")
plt.xticks(x_pos, x,rotation=90)
plt.show()
这是衡量不同层执行时间的正确方法吗?
【问题讨论】:
标签: python tensorflow keras tf.keras