Python:keras 形状不匹配错误

标签 python keras

我正在尝试在 keras 中构建一个非常简单的多层感知器 (MLP):

model = Sequential()
model.add(Dense(16, 8, init='uniform', activation='tanh'))
model.add(Dropout(0.5))
model.add(Dense(8, 2, init='uniform', activation='tanh'))

sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='mean_squared_error', optimizer=sgd)

model.fit(X_train, y_train, nb_epoch=1000, batch_size=50)
score = model.evaluate(X_test, y_test, batch_size=50)

我的训练数据形状:X_train.shape 给出 (34180, 16)

标签属于具有形状的二进制类:y_train.shape 给出 (34180,)

所以我的 keras 代码应该生成具有以下连接的网络:16x8 => 8x2

产生形状不匹配错误:

ValueError: Input dimension mis-match. (input[0].shape[1] = 2, input[1].shape[1] = 1)

Apply node that caused the error: Elemwise{sub,no_inplace}(Elemwise{Composite{tanh((i0 + i1))}}[(0, 0)].0, <TensorType(float64, matrix)>)
Inputs types: [TensorType(float64, matrix), TensorType(float64, matrix)]
Inputs shapes: [(50, 2), (50, 1)]
Inputs strides: [(16, 8), (8, 8)]

Epoch 0model.fit(X_train, y_train, nb_epoch=1000, batch_size=50)。我是否在监督 Keras 中明显的事情?

编辑: 我已经完成了问题 here但没有解决我的问题

最佳答案

我遇到了同样的问题,然后找到了这个帖子;

https://github.com/fchollet/keras/issues/68

您似乎声明了 2 的最终输出层,或者对于任何数量的类别,标签需要是分类类型,其中本质上这是每个观察的二进制向量,例如 3 类输出向量 [0,2 ,1,0,1,0] 变为 [[1,0,0],[0,0,1],[0,1,0],[1,0,0],[0,1,0] ,[1,0,0]].

np_utils.to_categorical 函数为我解决了这个问题;

from keras.utils import np_utils, generic_utils

y_train, y_test = [np_utils.to_categorical(x) for x in (y_train, y_test)]

关于Python:keras 形状不匹配错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31997366/

相关文章:

python - 将科学计数法转换为人类可读的 float

python - 类型 'NoneType' 的对象没有 len() Python

python - 使用多个不同长度和多个特征的时间序列时,如何为 LSTM 准备数据?

tensorflow - 多类分类问题中的不平衡类

python - 如何让 Keras 在 Anaconda 中使用 Tensorflow 后端?

python - 当使用 Python TensorFlow 输入形状 (53,))... 这个逗号是怎么回事?

python - Spyder IDE 看不到 pyspark 模块

python - 我可以在 python 中对内部函数进行单元测试吗?

python - PyYAML 和不寻常的标签

machine-learning - keras fit 与 keras 评估