【问题标题】:Correct way of measuring execution time of Keras layers测量 Keras 层执行时间的正确方法
【发布时间】:2020-11-28 04:12:28
【问题描述】:

我正在尝试检查 Keras 模型不同层的执行速度(使用 tensorflow 2.3.0 v 中的 keras)

我从repo 获取代码并对其进行了修改,以使用来自from timeit import default_timertimer() 计算时间

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


    【解决方案1】:

    我会说没有正确的方法来衡量不同层的执行时间,因为

    1. 神经网络作为一个整体发挥作用(整体大于部分之和)。您无法在不破坏系统的情况下从经过训练的网络中间拔出层,因此测量它处理某事的时间并不是特别有用。

    2. 一个层的执行时间也取决于前一层。如果您将先前的层从具有 1 个神经元更改为具有 [插入大量] 神经元,则即使该层本身保持不变,下一层的执行时间也会发生变化。所以基本上不可能测量一个层在日照中的执行时间。

    衡量一个合理的事情是,如果添加额外的层,执行时间会发生多少变化 - 比较有层的网络与没有层的网络的总体执行时间。但这需要您重新训练模型。

    您可以测量的另一件事是,当您向网络基础添加额外层时,执行时间会发生多少变化(类似于您正在做的事情,但仅将前 N 层的总体执行时间与 N 层的执行时间进行比较+1层)。当您考虑在进行迁移学习时要保留多少个基础层时,这可能会稍微有用(假设 NN 架构允许这样做),但即便如此,准确性也可能会成为决定因素,所以......

    【讨论】:

      猜你喜欢
      • 2011-09-08
      • 2012-05-14
      • 2023-04-07
      • 1970-01-01
      • 2018-12-08
      • 1970-01-01
      • 2019-09-06
      • 2016-12-25
      • 1970-01-01
      相关资源
      最近更新 更多