【发布时间】:2022-01-08 04:11:44
【问题描述】:
这是我的自定义softplus 激活:
def my_softplus(z):
return tf.math.log(tf.exp(tf.cast(z,tf.float32))+1)
如果我运行一个小测试:
my_softplus([-3.0, -1.0, 0.0, 2.0])
返回
<tf.Tensor: shape=(4,), dtype=float32, numpy=array([0.04858733, 0.31326166, 0.6931472 , 2.126928])>
当我运行 tensorflow 自己的 softplus 激活函数时:
tf.keras.activations.softplus([-3.0, -1.0, 0.0, 2.0])
我明白了
<tf.Tensor: shape=(4,), dtype=float32, numpy=array([0.04858736, 0.31326172, 0.6931472 , 2.126928 ], dtype=float32)>
非常相似的结果,除了最后一个数字不同。
当我在 mnist 数据集的子集上拟合以下模型时,
model2=models.Sequential()
model2.add(layers.Flatten(input_shape=(28,28)))
model2.add(layers.Dense(16, activation="softplus",#"softplus",# my_softplus <- this activation
kernel_initializer=my_glorot_initializer,
kernel_regularizer=my_l1_regularizer,
#kernel_constraint=my_positive_weights
))
model2.add(layers.Dense(16, activation="relu"))
model2.add(layers.Dense(10,activation="softmax"))
model2.compile(optimizer="rmsprop",loss=tf.keras.losses.SparseCategoricalCrossentropy(),
metrics=["accuracy"])
配件返回类似的东西
Epoch 1/20
20/20 - 2s - loss: -2.9399e-01 - accuracy: 0.1064 - val_loss: -2.1013e-01 - val_accuracy: 0.1136
Epoch 2/20
20/20 - 1s - loss: -9.9094e-02 - accuracy: 0.1064 - val_loss: 0.0140 - val_accuracy: 0.1136
但是,当我使用我的my_softplus 激活函数时,我得到 NaN 作为损失。
这是为什么呢?
注意:您可以将模型构建中的kernel_initializer和kernel_regularizer注释掉,结果会相似。
注意 2:这是带有 MWE 的 GoogleColab 笔记本的链接。
【问题讨论】:
-
Dense(1,activation="softmax")是错字吗? 1 没有意义,我猜你的意思是 10? -
@Frightera 我已经更新了模型构建。这是一个错字。我还改变了损失函数。我应该使用分类交叉熵的稀疏版本。
-
我在 Colab 上没有得到 NaN 损失,你能添加一个完整的可重现示例吗?
-
@Frightera 我在 colab 上重现了这个问题。检查我对问题的编辑。 ;)
标签: tensorflow tf.keras