Keras 添加归一化层,因此值的总和为 1
Keras add normalise layer so sum of values is 1
我希望能够在我的网络中添加一个层,该层从上一层获取输入并输出概率分布,其中所有值为正且总和为 1。因此所有负值都设置为 0,然后对剩余的正值进行归一化,使输出总和 = 1.
我该怎么做?
IIUC,你可以只使用 relu
和 softmax
激活函数:
import tensorflow as tf
inputs = tf.keras.layers.Input((5,))
x = tf.keras.layers.Dense(32, activation='relu')(inputs)
outputs = tf.keras.layers.Dense(32, activation='softmax')(x)
model = tf.keras.Model(inputs, outputs)
x = tf.random.normal((1, 5))
print(model(x))
print(tf.reduce_sum(model(x)))
tf.Tensor(
[[0.02258478 0.0218816 0.03778725 0.02707791 0.02791201 0.01847759
0.03252319 0.02181962 0.02726094 0.02221758 0.02674739 0.03611234
0.02821671 0.02606457 0.04022215 0.02933712 0.02975486 0.036876
0.04303711 0.03443421 0.03356075 0.03135845 0.03266712 0.03934086
0.02475732 0.04486758 0.02205345 0.0416355 0.04394628 0.03109134
0.03432642 0.03004995]], shape=(1, 32), dtype=float32)
tf.Tensor(1.0, shape=(), dtype=float32)
所以,如果 x
是你上一层的输出,你可以 运行:
x = tf.nn.relu(x)
x = tf.nn.softmax(x)
我希望能够在我的网络中添加一个层,该层从上一层获取输入并输出概率分布,其中所有值为正且总和为 1。因此所有负值都设置为 0,然后对剩余的正值进行归一化,使输出总和 = 1.
我该怎么做?
IIUC,你可以只使用 relu
和 softmax
激活函数:
import tensorflow as tf
inputs = tf.keras.layers.Input((5,))
x = tf.keras.layers.Dense(32, activation='relu')(inputs)
outputs = tf.keras.layers.Dense(32, activation='softmax')(x)
model = tf.keras.Model(inputs, outputs)
x = tf.random.normal((1, 5))
print(model(x))
print(tf.reduce_sum(model(x)))
tf.Tensor(
[[0.02258478 0.0218816 0.03778725 0.02707791 0.02791201 0.01847759
0.03252319 0.02181962 0.02726094 0.02221758 0.02674739 0.03611234
0.02821671 0.02606457 0.04022215 0.02933712 0.02975486 0.036876
0.04303711 0.03443421 0.03356075 0.03135845 0.03266712 0.03934086
0.02475732 0.04486758 0.02205345 0.0416355 0.04394628 0.03109134
0.03432642 0.03004995]], shape=(1, 32), dtype=float32)
tf.Tensor(1.0, shape=(), dtype=float32)
所以,如果 x
是你上一层的输出,你可以 运行:
x = tf.nn.relu(x)
x = tf.nn.softmax(x)