如何在 Keras 中指定带有数组列表的输入到嵌入层?

How to specify an input with a list of arrays to Embedding layer in Keras?

我正在尝试生成一些单词级别的文本,但遇到了以下问题:

我的输入是这样的:

   tokenized_seq = [[w2v_model.wv.vocab[word].index for word in w2v_data[i]] for i in range(len(w2v_data))]
   x_seq = []
   y_seq = []

   for seq in tokenized_seq:
      x_seq.append(seq[:-1])
      y_seq.append([seq[-1]])

因此,我将沿着序列(编码字 usnig word2vec)进行固定大小的滚动 window(标记化 _seq 是固定长度的序列列表)。

看例子:

代码块:

print(x_seq[0], '->', y_seq[0])  
print(' '.join([w2v_model.wv.index2word[i] for i in x_seq[0]]), '->', w2v_model.wv.index2word[y_seq[0].pop()]) 

输出:

[608, 1661, 1, 4260, 1, 3, 2978, 741, 0, 153, 740, 1, 12004] -> [109]
часть первая . i . — eh bien , mon prince . gênes -> et

所以,那么,我正在尝试将以上所有内容输入到嵌入层。

model = Sequential()
model.add(Embedding(input_dim=vocab_size,
                    output_dim=emdedding_size,
                    input_length=avg_sent_len-1,
                    weights=[predtrained_weights]
                    trainable=False))

model.add(Bidirectional(LSTM(units=128)))

model.add(Dense(units=vocab_size, activation='softmax'))

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

history = model.fit(x_seq, y_seq,
                   epochs=10,
                   batch_size=128,
                   validation_split=0.2,
                   verbose=2)

嵌入参数为:

predtrained_weights = w2v_model.wv.vectors
vocab_size, emdedding_size = w2v_model.wv.vectors.shape

avg_sent_lenx_seq

中每个sequence的len

模型编译良好,但拟合时出现以下错误:

ValueError: Error when checking target: expected dense_40 to have shape (31412,) but got array with shape (223396,) 

(31412,) 是 vocab_size 223396 是 x_seqy_seq 长度(输入序列的数量) 那么,有人可以帮助我吗?

您输入的 x_seq 应该是一个形状为 (batch_size, seq_len) 的 numpy 数组。尝试添加 x_seq = np.array(x_seq).