我正在尝试在TensorFlow 2.0中创建自定义神经网络模型。我知道,在TF2.0社区中一再建议,应该使用Functional API中的现有模块来构建自定义模型。
但是,在我的模型中,要求一个隐藏层具有具有不同激活功能的神经元。例如,我想要一个具有三个神经元的隐藏层,其中一个是线性的,另外两个是S型的。最终的模型只是重复将此层堆叠N次。
tf.keras.layers模块中没有适当的功能来实现上述功能。有没有办法使用类似MyDenseLayer(tf.keras.layers.Layer)的类定义自己实现此目的?然后,通过堆叠此自定义图层,我很容易构建完整的模型。
您可以执行以下操作,
import tensorflow as tf
from tensorflow.keras.layers import Input, Lambda, Activation, Dense
from tensorflow.keras.models import Model
def f(x):
return tf.stack([a(c) for c,a in zip(tf.unstack(x[0], axis=1), x[1])], axis=1)
inp = Input(shape=(10,))
out = Dense(3)(inp)
out = Lambda(lambda x: f(x))(
[out, [Activation('linear'), Activation('sigmoid'), Activation('sigmoid')]]
)
model = Model(inputs=inp, outputs=out)
说明:
诀窍在Lambda
层中。
Dense
上分割输出axis=1
。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句