使用 TensorFlow 估计器 DNNClassifier 的多个激活函数

数据挖掘 机器学习 Python 张量流
2021-09-28 22:01:38

我只想知道是否可以将tf.estimator.DNNClassifier与多个不同的激活函数一起使用。我的意思是,我可以使用对不同层使用不同激活函数的 DNNClassifier 估计器吗?

例如,如果我有一个三层模型,我可以将第一层使用sigmoid函数,第二层使用ReLu函数,最后使用tanh函数吗?

我想知道是否无法使用DNNClassifier做到这一点,我怎样才能通过简单的方式做到这一点。

1个回答

所以这是一个非常古老的问题,但对于来自 Google 的任何人来说:

根据 Tensor Flow 提供的文档,tf.estimator.DNNClassifier具有以下activation_fn描述的参数:

Activation function applied to each layer. If None, will use tf.nn.relu

因此,该模型仅采用一个激活函数并在所有层上使用它。话虽如此,Tensor Flow 指出:

Warning: Estimators are not recommended for new code. Estimators run v1.Session-style code which is more difficult to write correctly, and can behave unexpectedly, especially when combined with TF 2 code. Estimators do fall under our compatibility guarantees, but will receive no fixes other than security vulnerabilities. See the migration guide for details.

因此,为了解决这个问题并与 Tensor Flow 的建议兼容,可以使用 keras 逐层创建所需的 DNN。如这里的示例所示

import tensorflow as tf

inputs = tf.keras.Input(shape=(3,))
x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs)
outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)

可以在创建每一层时指定每一层的激活函数。有关 keras.layers 的更多信息,请参见此处