簡體   English   中英

Keras LSTM 模型中的輸入形狀和擬合

[英]The input shape and fitting in Keras LSTM model

我正在學習 LSTM 模型以使數據集適合多類分類,即八種音樂流派,但不確定 Keras 模型中的輸入形狀。

我已經按照這里的教程進行操作:

  1. 如何重塑 LSTM 模型的輸入數據
  2. 使用 Keras 深度學習庫的多類分類教程
  3. 使用 Keras 在 Python 中使用 LSTM 循環神經網絡進行序列分類

我的數據是這樣的:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM