使用预训练嵌入的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

关于k折交叉验证的直观问题

我在使用交叉验证检查预测能力时遇到了一些直观问题,我认…

调整numpy数组大小以使用sklearn的train_test_split函数?

我正在尝试使用sklearn中的test_train_…

如何转换二维张量和索引张量以便用于torch.nn.utils.rnn.pack_sequence

我有一组序列,格式如下: sequences = to…

模型预测值的含义是什么?

我在网上找到一个数字识别器的CNN模型并进行了训练,当…

锯齿张量作为LSTM的输入

了解锯齿张量以及如何在TensorFlow中使用它们。…

如何告诉SciKit的LinearRegression模型预测值不能小于零?

我有以下代码,尝试根据非价格基础特征来估值股票。 pr…

发表回复

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