keras多维输入到simpleRNN:维度不匹配

时间:2017-07-25 07:21:17

标签: python-3.x machine-learning keras mismatch

输入元素有3行,每行有199列,输出有46行和1列

Input.shape, output.shape
((204563, 3, 199), (204563, 46, 1))

当输入时,抛出以下错误:

from keras.layers import Dense
from keras.models import Sequential
from keras.layers.recurrent import SimpleRNN

model = Sequential()
model.add(SimpleRNN(100, input_shape = (Input.shape[1], Input.shape[2])))
model.add(Dense(output.shape[1], activation = 'softmax'))
model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])
model.fit(Input, output, epochs = 20, batch_size = 200)

错误抛出:

Epoch 1/20

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-134-378dd431cf45> in <module>()
      3 model.add(Dense(y_target.shape[1], activation = 'softmax'))
      4 model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])
----> 5 model.fit(X_input, y_target, epochs = 20, batch_size = 200)
.
.
.
ValueError: Error when checking model target: expected dense_6 to have 2 dimensions, but got array with shape (204563, 46, 1)

请解释问题的原因和可能的原因

1 个答案:

答案 0 :(得分:2)

问题是SimpleRNN(100)会返回一个形状张量(204563, 100),因此,Dense(46)(因为output.shape[1]=46)会返回一个形状张量(204563, 46) ,但您的y_target形状为(204563, 46, 1)。您需要删除最后一个维度,例如y_target = np.squeeze(y_target),以便维度一致