Python 将多个输入传递到Keras模型时出错
我想使用Keras训练一个二进制分类器,我的训练数据是shapePython 将多个输入传递到Keras模型时出错,python,machine-learning,neural-network,keras,classification,Python,Machine Learning,Neural Network,Keras,Classification,我想使用Keras训练一个二进制分类器,我的训练数据是shape(2000,2128)和shape(2000,)的标签作为Numpy数组 其思想是训练这样一种情况,即在单个数组中嵌入在一起意味着它们要么相同,要么不同,分别使用0或1进行标记 培训数据如下所示: 标签看起来像[1 1 0 0 1 0..] 代码如下: import keras from keras.layers import Input, Dense from keras.models import Model frst_i
(2000,2128)
和shape(2000,)
的标签作为Numpy数组
其思想是训练这样一种情况,即在单个数组中嵌入在一起意味着它们要么相同,要么不同,分别使用0或1进行标记
培训数据如下所示:
标签看起来像[1 1 0 0 1 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).调用fit
方法时,传递对应于两个输入层的两个数组的列表。不要将softmax
用作最后一层的激活。否则,由于它有一个单元,它将始终输出1。改用sigmoid
。