如何在Keras中缓存层激活?

5

我在Keras中训练了一个神经网络,其中前几层的权重是固定的(不可训练的)。

这些层所执行的计算在训练过程中非常密集。为了节省计算时间,可以对每个输入缓存层激活,并在下一个epoch传递相同的输入数据时重复使用。

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

1个回答

4
你可以将你的模型分成两个不同的模型。例如,在以下代码片段中,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不支持我需要的功能。 - roman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接