我希望能夠向我的網路添加一個層,該層從前一層獲取輸入并輸出概率分布,其中所有值均為正且總和為 1。因此,任何負值都設定為 0,然后是剩余的正值歸一化,使得輸出的總和 = 1。
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/453222.html
