[英]The input shape and fitting in Keras LSTM model
我正在学习 LSTM 模型以使数据集适合多类分类,即八种音乐流派,但不确定 Keras 模型中的输入形状。
我已经按照这里的教程进行操作:
我的数据是这样的:
vector_1,vector_2,...vector_30,genre
23.5 20.5 3 pop
.
.
.
(7678)
我将数据形状转换为 (7678,1,30),即 7678 首音乐、1 个时间步和 30 个向量。 对于音乐流派,我使用了train_labels = pd.get_dummies(df['genre'])
这是我的模型:
# build a sequential model
model = Sequential()
# keras convention to use the (1,30) from the scaled_train
model.add(LSTM(32,input_shape=(1,30),return_sequences=True))
model.add(LSTM(32,return_sequences=True))
model.add(LSTM(32))
# to avoid overfitting
model.add(Dropout(0.3))
# output layer
model.add(Dense(8,activation='softmax'))
model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['accuracy'])
拟合模型
model.fit(scaled_train,train_labels,epochs=5,validation_data=(scaled_validation,valid_labels))
但是在尝试拟合模型时,我收到错误ValueError: Shapes (None, 8) and (None, 1, 8) are incompatible
。 我在代码中做错了什么吗? 任何帮助都受到高度赞赏。
我的数据的形状
print(scaled_train.shape)
print(train_labels.shape)
print(scaled_validation.shape)
print(valid_labels.shape)
(7678, 1, 30)
(7678, 8)
(450, 30)
(450, 8)
编辑
我试过如何在 keras 中堆叠多个 lstm? 但是,仍然得到错误ValueError: Input 0 of layer sequential_21 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [None, 30]
ValueError: Input 0 of layer sequential_21 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [None, 30]
顾名思义, return_sequences=True
将返回一个序列(带有时间步长),这就是为什么你的输出形状是(None, 1, 8)
:时间步长被保持。 当它穿过致密层时,它不会自动变平。 尝试:
model = Sequential()
model.add(LSTM(32,input_shape=(1,30),return_sequences=False))
model.add(Dense(32,activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(8,activation='softmax'))
我想如果您取消注释第二个 LSTM 层,这不会发生?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.