Keras-LSTM模型的输入形状与拟合

2024-04-27 01:07:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习LSTM模型,以使数据集适合多类别分类,这是八种音乐类型,但不确定Keras模型中的输入形状

我在这里学习了教程:

  1. How to reshape input data for LSTM model
  2. Multi-Class Classification Tutorial with the Keras Deep Learning Library
  3. Sequence Classification with LSTM Recurrent Neural Networks in Python with 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)

编辑

我试过了How to stack multiple lstm in keras? 但是仍然要得到错误ValueError: Input 0 of layer sequential_21 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [None, 30]


Tags: theto数据模型addlabelsmodel音乐
1条回答
网友
1楼 · 发布于 2024-04-27 01:07:38

顾名思义,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层的注释,这不会发生

相关问题 更多 >