使用预训练嵌入的Keras自编码器返回错误的维数

我尝试复制一个基于《Deep Learning with Keras》书中一个示例的句子自编码器。

我重新编写了该示例,使用嵌入层代替句子生成器,并使用fit而不是fit_generator

我的代码如下:

df_train_text = df['string']max_length = 80embedding_dim = 300latent_dim = 512batch_size = 64num_epochs = 10# prepare tokenizert = Tokenizer(filters='')t.fit_on_texts(df_train_text)word_index = t.word_indexvocab_size = len(t.word_index) + 1# integer encode the documentsencoded_train_text = t.texts_to_matrix(df_train_text)padded_train_text = pad_sequences(encoded_train_text, maxlen=max_length, padding='post')padding_train_text = np.asarray(padded_train_text, dtype='int32')embeddings_index = {}f = open('/Users/embedding_file.txt')for line in f:    values = line.split()    word = values[0]    coefs = np.asarray(values[1:], dtype='float32')    embeddings_index[word] = coefsf.close()print('Found %s word vectors.' % len(embeddings_index))#Found 51328 word vectors.embedding_matrix = np.zeros((vocab_size, embedding_dim))for word, i in word_index.items():    embedding_vector = embeddings_index.get(word)    if embedding_vector is not None:        # words not found in embedding index will be all-zeros.        embedding_matrix[i] = embedding_vectorembedding_layer = Embedding(vocab_size,                            embedding_dim,                            weights=[embedding_matrix],                            input_length=max_length,                            trainable=False)inputs = Input(shape=(max_length,), name="input")embedding_layer = embedding_layer(inputs)encoder = Bidirectional(LSTM(latent_dim), name="encoder_lstm", merge_mode="sum")(embedding_layer)decoder = RepeatVector(max_length)(encoder)decoder = Bidirectional(LSTM(embedding_dim, name='decoder_lstm', return_sequences=True), merge_mode="sum")(decoder)autoencoder = Model(inputs, decoder)autoencoder.compile(optimizer="adam", loss="mse")autoencoder.fit(padded_train_text, padded_train_text,                epochs=num_epochs,                 batch_size=batch_size,                callbacks=[checkpoint])

我确认了我的层形状与示例中的相同,但是当我尝试拟合我的自编码器时,我得到了以下错误:

ValueError: Error when checking target: expected bidirectional_1 to have 3 dimensions, but got array with shape (36320, 80)

我还尝试了一些其他方法,包括将texts_to_matrix切换为texts_to_sequence,以及是否包装我的填充字符串。

我还看到了这个帖子,似乎表明我这样做是错误的。是否有可能像我编写的这样使用嵌入层来拟合自编码器?如果不能,有人能帮助解释提供的示例和我版本之间的根本区别吗?

编辑:我在最后一层中删除了return_sequences=True参数后,得到以下错误:ValueError: Error when checking target: expected bidirectional_1 to have shape (300,) but got array with shape (80,)

在更新我的层形状后:

_________________________________________________________________Layer (type)                 Output Shape              Param #   =================================================================input (InputLayer)           (None, 80)                0         _________________________________________________________________embedding_8 (Embedding)      (None, 80, 300)           2440200   _________________________________________________________________encoder_lstm (Bidirectional) (None, 512)               3330048   _________________________________________________________________repeat_vector_8 (RepeatVecto (None, 80, 512)           0         _________________________________________________________________bidirectional_8 (Bidirection (None, 300)               1951200   =================================================================Total params: 7,721,448Trainable params: 5,281,248Non-trainable params: 2,440,200_________________________________________________________________

我在RepeatVector层和模型的最后一层之间是否遗漏了一个步骤,以便我可以返回形状为(None, 80, 300)而不是当前生成的(None, 300)形状?


回答:

Embedding层以整数序列(即词索引)作为输入,形状为(num_words,),并输出对应的嵌入,形状为(num_words, embd_dim)。因此,在给定文本上拟合Tokenizer实例后,您需要使用其texts_to_sequences()方法将每个文本转换为整数序列:

encoded_train_text = t.texts_to_sequences(df_train_text)

此外,由于填充encoded_train_text后其形状将为(num_samples, max_length),网络的输出形状也必须具有相同的形状(即因为我们正在创建自编码器),因此您需要删除最后一层的return_sequences=True参数。否则,它将给我们一个三维张量作为输出,这没有意义。

作为补充说明,以下行是多余的,因为padded_train_text已经是numpy数组(顺便说一下,您根本没有使用padding_train_text):

padding_train_text = np.asarray(padded_train_text, dtype='int32')

Related Posts

如何从数据集中移除EXIF数据?

我在尝试从数据集中的图像中移除EXIF数据(这些数据将…

用于Python中的“智能点”游戏的遗传算法不工作

过去几天我一直在尝试实现所谓的“智能点”游戏。我第一次…

哪个R平方得分更有帮助?

data.drop(‘Movie Title’, ax…

使用线性回归预测GRE分数对录取率的影响

我正在学习线性回归,并尝试在Jupyter笔记本中用P…

使用mlrMBO贝叶斯优化进行SVM超参数调优时出现错误

我试图针对一个分类任务优化SVM,这个方法在许多其他模…

Keras模型的二元交叉熵准确率未发生变化

我在网上看到了很多关于这个问题的提问,但没有找到明确的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注