【问题标题】:How to cache layer activations in Keras?如何在 Keras 中缓存层激活?
【发布时间】:2019-01-29 23:26:49
【问题描述】:

我训练了一个神经网络,其中第一层在 Keras 中具有固定权重(不可训练)。

这些层执行的计算在训练期间非常密集。为每个输入缓存层激活并在下一个 epoch 传递相同的输入数据时重用它们以节省计算时间是有意义的。

是否有可能在 Keras 中实现这种行为?

【问题讨论】:

    标签: python keras


    【解决方案1】:

    您可以将模型分成两个不同的模型。例如,在以下 sn-p x_ 将对应于您的中间激活:

    from keras.models import Model
    from keras.layers import Input, Dense
    import numpy as np
    
    
    nb_samples = 100
    in_dim = 2
    h_dim = 3
    out_dim = 1
    
    a = Input(shape=(in_dim,))
    b = Dense(h_dim, trainable=False)(a)
    model1 = Model(a, b)
    model1.compile('sgd', 'mse')
    
    c = Input(shape=(h_dim,))
    d = Dense(out_dim)(c)
    model2 = Model(c, d)
    model2.compile('sgd', 'mse')
    
    
    x = np.random.rand(nb_samples, in_dim)
    y = np.random.rand(nb_samples, out_dim)
    x_ = model1.predict(x)  # Shape=(nb_samples, h_dim)
    
    model2.fit(x_, y)
    

    【讨论】:

    • 谢谢!这就是我最终要做的,因为看起来 Keras 不支持我首先需要的功能。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 2019-05-09
    相关资源
    最近更新 更多