简体   繁体   English

如何在Keras中为每个输出应用S型函数?

[英]How to apply sigmoid function for each outputs in Keras?

This is part of my codes. 这是我的代码的一部分。

model = Sequential()
model.add(Dense(3, input_shape=(4,), activation='softmax'))
model.compile(Adam(lr=0.1),
          loss='categorical_crossentropy',
          metrics=['accuracy'])

with this code, it will apply softmax to all the outputs at once. 使用此代码,它将立即将softmax应用于所有输出。 So the output indicates probability among all. 因此,输出表明了所有可能性。 However, I am working on non-exclusive classifire, which means I want the outputs to have independent probability. 但是,我正在研究非排他性classifire,这意味着我希望输出具有独立的概率。 Sorry my English is bad... But what I want to do is to apply sigmoid function to each outputs so that they will have independent probabilities. 抱歉,我的英语不好。但是我想要做的是对每个输出应用S形函数,以便它们具有独立的概率。

There is no need to create 3 separate outputs like suggested by the accepted answer. 无需创建3个单独的输出(如已接受的答案所建议)。

The same result can be achieved with just one line: 只需一行就可以达到相同的结果:

model.add(Dense(3, input_shape=(4,), activation='sigmoid'))

You can just use 'sigmoid' activation for the last layer: 您可以在最后一层使用'sigmoid'激活:

from tensorflow.keras.layers import GRU
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation
import numpy as np

from tensorflow.keras.optimizers import Adam

model = Sequential()
model.add(Dense(3, input_shape=(4,), activation='sigmoid'))
model.compile(Adam(lr=0.1),
          loss='categorical_crossentropy',
          metrics=['accuracy'])

pred = model.predict(np.random.rand(5, 4))
print(pred)

Output of independent probabilities: 输出独立概率:

[[0.58463055 0.53531045 0.51800555]
 [0.56402034 0.51676977 0.506389  ]
 [0.665879   0.58982867 0.5555959 ]
 [0.66690147 0.57951677 0.5439698 ]
 [0.56204814 0.54893976 0.5488999 ]]

As you can see the classes probabilities are independent from each other. 如您所见,类的概率彼此独立。 The sigmoid is applied to every class separately. 乙状结肠分别应用于每个类别。

You can try using Functional API to create a model with n outputs where each output is activated with sigmoid . 您可以尝试使用Functional API创建具有n个输出的模型,其中每个输出都通过sigmoid激活。

You can do it like this 你可以这样

in = Input(shape=(4, ))

dense_1 = Dense(units=4, activation='relu')(in)

out_1 = Dense(units=1, activation='sigmoid')(dense_1)
out_2 = Dense(units=1, activation='sigmoid')(dense_1)
out_3 = Dense(units=1, activation='sigmoid')(dense_1)

model = Model(inputs=[in], outputs=[out_1, out_2, out_3])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM