簡體   English   中英

將多個輸入傳遞給Keras模型時出錯

[英]Error passing multiple inputs into Keras model

我想使用(2000,2,128)訓練一個二進制分類器,我的訓練數據是形狀(2000,2,128)和形狀標簽(2000,)作為Numpy數組。

進行訓練的想法是,將嵌入在一起形成單個數組意味着它們相同或不同,分別用0或1標記。

訓練數據如下: [[[0 1 2 ....128][129.....256]][[1 2 3 ...128][9 9 3 5...]].....] ,標簽看起來像[1 1 0 0 1 1 0 0..]

這是代碼:

import keras
from keras.layers import Input, Dense

from keras.models import Model

frst_input = Input(shape=(128,), name='frst_input')
scnd_input = Input(shape=(128,),name='scnd_input')
x = keras.layers.concatenate([frst_input, scnd_input])
x = Dense(128, activation='relu')(x)
x=(Dense(1, activation='softmax'))(x)
model=Model(inputs=[frst_input, scnd_input], outputs=[x])
model.compile(optimizer='rmsprop', loss='binary_crossentropy',
              loss_weights=[ 0.2],metrics=['accuracy'])

運行此代碼時出現以下錯誤:

ValueError: Error when checking model input: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 2 array(s), but instead got the following list of 1 arrays: [array([[[ 0.07124118, -0.02316936, -0.12737238, ...,  0.15822273,
      0.00129827, -0.02457245],
    [ 0.15869428, -0.0570458 , -0.10459555, ...,  0.0968155 ,
      0.0183982 , -0.077924...

我該如何解決這個問題? 我的代碼使用兩個輸入進行分類訓練分類器是否正確?

好吧,這里有兩個選擇:

1)將訓練數據重整為(2000, 128*2)並僅定義一個輸入層:

X_train = X_train.reshape(-1, 128*2)

inp = Input(shape=(128*2,))
x = Dense(128, activation='relu')(inp)
x = Dense(1, activation='sigmoid'))(x)
model=Model(inputs=[inp], outputs=[x])

2)定義兩個輸入層,就像已經完成的那樣,並在調用fit方法時傳遞兩個輸入數組的列表

# assuming X_train have a shape of `(2000, 2, 128)` as you suggested
model.fit([X_train[:,0], X_train[:,1]], y_train, ...)

此外,由於您在這里進行二進制分類,因此您需要使用sigmoid作為最后一層的激活(即,在這種情況下使用softmax將始終輸出1,因為softmax將輸出歸一化,以使其總和等於1)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM