在tf.keras中,使用softmax作为顺序层和使用softmax作为密集层的激活函数有什么区别?
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
并且
tf.keras.layers.Softmax(10)
在tf.keras中,使用softmax作为顺序层和使用softmax作为密集层的激活函数有什么区别?
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
并且
tf.keras.layers.Softmax(10)
它们是相同的,您可以自行测试
# 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,则可以更改此设置。您可以在第二个选项中轻松更改此设置。