将多个输入传递到Keras模型时出现错误

我想使用Keras训练一个二元分类器,我的训练数据形状为(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 kerasfrom keras.layers import Input, Densefrom keras.models import Modelfrst_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方法时传递一个包含两个输入数组的列表

# 假设X_train的形状为`(2000, 2, 128)`,如你所述model.fit([X_train[:,0], X_train[:,1]], y_train, ...)

此外,由于你在这里进行的是二元分类,你需要在最后一层使用sigmoid作为激活函数(即在这种情况下使用softmax总是会输出1,因为softmax会将输出标准化,使它们的总和等于1)。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注