python - 将多个输入传递到 Keras 模型时出错

标签 python machine-learning neural-network keras classification

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

相关文章:

python - 如何在 Linux 上修复 Python 中的 Except 错误

tensorflow - 使用 GradientTape() 计算 TensorFlow v.2 中的雅可比矩阵

java - 我的神经网络有更好的激活函数吗?

python - 使用 Beautifulsoup 查找文本的精确匹配

Python S3 上传签名不匹配

python - 使用递归选择偶数

python - 计算 sklearn 中无监督 LOF 的 AUC

python - 如何从 kNeighborsClassifier 中查找前 n 个匹配项?

artificial-intelligence - 我们如何初始化 Hopfield 神经网络?

python - Tensorflow 神经网络在训练后总是有 50% 的把握