我想使用 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 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) 将训练数据 reshape 为 (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)。
关于python - 将多个输入传递到 Keras 模型时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52858515/