我想使用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)。