Keras 添加归一化层,因此值的总和为 1
tensorflow 374
原文标题 :Keras add normalise layer so sum of values is 1
我希望能够在我的网络中添加一个层,该层从前一层获取输入并输出一个概率分布,其中所有值都是正数并且总和为 1。所以任何负值都设置为 0,然后是剩余的正值归一化,使得输出的总和 = 1。
我怎样才能做到这一点?
回复
我来回复-
AloneTogether 评论
该回答已被采纳!
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)
2年前