![](/img/trans.png)
[英]Training and evaluating accuracies different in keras LSTM model: why does evaluation not produce same results as during training?
[英]Training the same model with two different outputs with Keras
我在 python 中有一個用 Keras 編碼的簡單 GRU.network,如下所示:
gru1 = GRU(16, activation='tanh', return_sequences=True)(input)
dense = TimeDistributed(Dense(16, activation='tanh'))(gru1)
output = TimeDistributed(Dense(1, activation="sigmoid"))(dense)
我對 output 使用了 sigmoid 激活,因為我的目的是分類。 但我也需要使用相同的 model 進行回歸。 我需要將 output 激活更改為線性。 但是.net的rest還是老樣子。 所以在這種情況下,我將使用兩個不同的 .networks 來實現兩個不同的目的。 輸入是相同的。 但是輸出是 sigmoid 的類和線性激活的值。
我的問題是,有沒有辦法只使用 one.network 但最后得到兩個不同的輸出? 謝謝。
是的,您可以使用功能 API 設計多輸出 model。您可以保留共享層和 2 個不同的輸出,一個帶有 sigmoid,另一個帶有線性激活。
注意:不要將input
用作變量,它是 python 中的 function 名稱。
from tensorflow.keras.layers import *
from tensorflow.keras.models import Model
seq_len = 100 # your sequence length
input_ = Input(shape=(seq_len,1))
gru1 = GRU(16, activation='tanh', return_sequences=True)(input_)
dense = TimeDistributed(Dense(16, activation='tanh'))(gru1)
output1 = TimeDistributed(Dense(1, activation="sigmoid", name="out1"))(dense)
output2 = TimeDistributed(Dense(1, activation="linear", name="out2"))(dense)
model = Model(input_, [output1, output2])
model.summary()
Model: "model_1"
__________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
==================================================================================================
input_3 (InputLayer) [(None, 100, 1)] 0
__________________________________________________________________________________________________
gru_2 (GRU) (None, 100, 16) 912 input_3[0][0]
__________________________________________________________________________________________________
time_distributed_3 (TimeDistrib (None, 100, 16) 272 gru_2[0][0]
__________________________________________________________________________________________________
time_distributed_4 (TimeDistrib (None, 100, 1) 17 time_distributed_3[0][0]
__________________________________________________________________________________________________
time_distributed_5 (TimeDistrib (None, 100, 1) 17 time_distributed_3[0][0]
==================================================================================================
Total params: 1,218
Trainable params: 1,218
Non-trainable params: 0
使用兩個損失函數進行編譯:
losses = {
"out1": "binary_crossentropy",
"out2": "mse",
}
# initialize the optimizer and compile the model
model.compile(optimizer='adam', loss=losses, metrics=["accuracy", "mae"])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.