![](/img/trans.png)
[英]ValueError: Error when checking target: expected PREDICTIONS to have 4 dimensions, but got array with shape (20, 131) [Keras]
[英]Keras Embedding layer - ValueError: Error when checking input: expected to have 2 dimensions, but got (39978, 20, 20)
我正在嘗試在 keras 中創建一個 LSTM/GRU 模型,以將給定的文章分類為 4 個類別之一。
input > embedding layer > LSTM/GRU layer > [context vector] > Dense(softmax activation) > output class
在訓練輸入數據中有 39978 篇文章,每篇文章有 20 個句子,每個句子有 20 個單詞。 至於目標變量,有 4 個目標類。
x_train.shape
是(39978, 20, 20)
和
y_train.shape
是(39978, 4)
embedding_matrix.shape
is (27873, 100)
embedding_matrix 是在詞匯表上用glove.6B.100d.txt創建的
我正在嘗試創建一個如下所示的順序模型
vocab_size = len(tokenizer.word_index.keys()) # 27873
MAX_SENT_LENGTH = 20
model = Sequential()
embedding_dimentations = embedding_matrix.shape[1]
e = Embedding(vocab_size,
embedding_dimentations,
weights=[embedding_matrix],
input_length=MAX_SENT_LENGTH,
trainable=False)
model.add(e)
model.add(Bidirectional(GRU(embedding_dimentations, dropout=0.25, recurrent_dropout=0.25)))
model.add(Dense(4, activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
在上面的模型上,如果我適合
batch_size = 128
epochs = 3
print('Training.....')
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
validation_split=.2)
我收到以下錯誤
ValueError:檢查輸入時出錯:預期 embedding_6_input 有 2 個維度,但得到了形狀為 (39978, 20, 20) 的數組
我嘗試在 Embedding() 中指定輸入形狀元組,但它不起作用。 有人可以指出我正確的方向嗎?
謝謝
vocab_size = len(tokenizer.word_index.keys()) # 27873
MAX_SENT_LENGTH = 20
embedding_dimentations = embedding_matrix.shape[1]
model = Sequential()
encoder_inputs = Input(shape=(20, 20))
x1 = Reshape((400,))(encoder_inputs)
x2 = Embedding(vocab_size,
embedding_dimentations,
weights=[embedding_matrix],
input_length=400,
trainable=False)(x1)
# should use Bidirectional GRU
encoder = GRU(embedding_dimentations, dropout=0.25, recurrent_dropout=0.25, return_state=True)
encoder_outputs, state_h = encoder(x2)
predictions = Dense(4, activation='softmax')(encoder_outputs)
model = Model(inputs=encoder_inputs, outputs=predictions)
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
在 Embedding 層之前使用 Reshape 層將數據轉換為正確的形狀。 這種方法對我有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.