2017-05-18 91 views
7

我有一個問題,當給定一個預測變量向量時,我會處理預測兩個輸出。 假設預測向量看起來像x1, y1, att1, att2, ..., attn,它表示x1, y1是座標,而att's是附加到x1, y1座標出現處的其他屬性。基於這個預測集,我想預測x2, y2。這是一個時間序列問題,我試圖使用多重回歸來解決。 我的問題是我如何設置keras,它可以在最後一層給我2個輸出。我已經解決了keras中的簡單迴歸問題,代碼在my github中可用。Keras中的多個輸出

回答

11
from keras.models import Model 
from keras.layers import *  

#inp is a "tensor", that can be passed when calling other layers to produce an output 
inp = Input((10,)) #supposing you have ten numeric values as input 


#here, SomeLayer() is defining a layer, 
#and calling it with (inp) produces the output tensor x 
x = SomeLayer(blablabla)(inp) 
x = SomeOtherLayer(blablabla)(x) #here, I just replace x, because this intermediate output is not interesting to keep 


#here, I want to keep the two different outputs for defining the model 
#notice that both left and right are called with the same input x, creating a fork 
out1 = LeftSideLastLayer(balbalba)(x)  
out2 = RightSideLastLayer(banblabala)(x) 


#here, you define which path you will follow in the graph you've drawn with layers 
#notice the two outputs passed in a list, telling the model I want it to have two outputs. 
model = Model(inp, [out1,out2]) 
model.compile(optimizer = ...., loss = ....) #loss can be one for both sides or a list with different loss functions for out1 and out2  

model.fit(inputData,[outputYLeft, outputYRight], epochs=..., batch_size=...) 
+0

所以,如果我理解你正確地,那麼你的意思是: 'InputShape =(10)'' = model_1順序() model_1.add(密集(250,激活= '正切',input_shape =(InputShape))) model_1.add(Dense(2,activation ='relu')) model_1.compile(optimizer ='adam',loss ='mse',metrics = ['accuracy'])model_1。適合(預測者,目標,時代=任何,....)' 。我的問題是,這是如何不同於你的,你只是指定兩個輸出。 –

+2

對我的回答添加了評論:) - 您無法使用順序模型創建分支,這根本不可能。 –

+0

@Daniel嗨丹尼爾,你可以擴展嗎?我正在尋找的是有一個網絡,試圖預測兩個不同的東西,所以我想象一個分支發生在我的倒數第二層,它進入兩個不同的softmax層,然後連接這兩層的結果,然後backpropogate就此而言。這在keras中是不可能的嗎? – tryingtolearn