在tf.keras中,使用softmax作为顺序层和在密集层中使用softmax作为激活函数有什么区别?

8

在tf.keras中,使用softmax作为顺序层和使用softmax作为密集层的激活函数有什么区别?

tf.keras.layers.Dense(10, activation=tf.nn.softmax)

并且

tf.keras.layers.Softmax(10)
1个回答

6

它们是相同的,您可以自行测试

# generate data
x = np.random.uniform(0,1, (5,20)).astype('float32')

# 1st option
X = Dense(10, activation=tf.nn.softmax)
A = X(x)

# 2nd option
w,b = X.get_weights()
B = Softmax()(tf.matmul(x,w) + b)

tf.reduce_all(A == B)
# <tf.Tensor: shape=(), dtype=bool, numpy=True>

当使用tf.keras.layers.Softmax时,也要注意它不需要指定单元数,它是一个简单的激活函数。

默认情况下,softmax 在 -1 轴上计算,如果您有张量输出 > 2D 并且想在其他维度上操作 softmax,则可以更改此设置。您可以在第二个选项中轻松更改此设置。


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