简体   繁体   English

将多个输入传递给Keras模型时出错

[英]Error passing multiple inputs into Keras model

I want to train a binary classifier using Keras and my training data is of shape (2000,2,128) and labels of shape (2000,) as Numpy arrays. 我想使用(2000,2,128)训练一个二进制分类器,我的训练数据是形状(2000,2,128)和形状标签(2000,)作为Numpy数组。

The idea is to train such that embeddings together in a single array means they are either same or different, labelled using 0 or 1 respectively. 进行训练的想法是,将嵌入在一起形成单个数组意味着它们相同或不同,分别用0或1标记。

The training data looks like: [[[0 1 2 ....128][129.....256]][[1 2 3 ...128][9 9 3 5...]].....] and the labels looks like [1 1 0 0 1 1 0 0..] . 训练数据如下: [[[0 1 2 ....128][129.....256]][[1 2 3 ...128][9 9 3 5...]].....] ,标签看起来像[1 1 0 0 1 1 0 0..]

Here is the code: 这是代码:

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'])

I am getting the following error while running this code: 运行此代码时出现以下错误:

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...

How can I resolve this issue? 我该如何解决这个问题? Is my code correct to train the classifier using two inputs to classify? 我的代码使用两个输入进行分类训练分类器是否正确?

Well, you have two options here: 好吧,这里有两个选择:

1) Reshape the training data to (2000, 128*2) and define only one input layer: 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) Define two input layers, as you have already done, and pass a list of two input arrays when calling fit method: 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, ...)

Further, since you are doing binary classification here, you need to use sigmoid as the activation of last layer (ie using softmax in this case would always outputs 1, since softmax normalizes the outputs such that their sum equals to one). 此外,由于您在这里进行二进制分类,因此您需要使用sigmoid作为最后一层的激活(即,在这种情况下使用softmax将始终输出1,因为softmax将输出归一化,以使其总和等于1)。

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

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