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

keras multi dimensions input to simpleRNN: dimension 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)

请说明问题原因及可能的解决方案

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