tensorflow - 将嵌入层添加到 lstm 自动编码器时出错
问题描述
我有一个运行良好的 seq2seq 模型。我想在这个网络中添加一个嵌入层,但我遇到了错误。
这是我使用预训练词嵌入的架构,效果很好(实际上代码与此处可用的代码几乎相同,但我想在模型中包含嵌入层,而不是使用预训练的嵌入向量):
LATENT_SIZE = 20
inputs = Input(shape=(SEQUENCE_LEN, EMBED_SIZE), name="input")
encoded = Bidirectional(LSTM(LATENT_SIZE), merge_mode="sum", name="encoder_lstm")(inputs)
encoded = Lambda(rev_ent)(encoded)
decoded = RepeatVector(SEQUENCE_LEN, name="repeater")(encoded)
decoded = Bidirectional(LSTM(EMBED_SIZE, return_sequences=True), merge_mode="sum", name="decoder_lstm")(decoded)
autoencoder = Model(inputs, decoded)
autoencoder.compile(optimizer="sgd", loss='mse')
autoencoder.summary()
NUM_EPOCHS = 1
num_train_steps = len(Xtrain) // BATCH_SIZE
num_test_steps = len(Xtest) // BATCH_SIZE
checkpoint = ModelCheckpoint(filepath=os.path.join('Data/', "simple_ae_to_compare"), save_best_only=True)
history = autoencoder.fit_generator(train_gen, steps_per_epoch=num_train_steps, epochs=NUM_EPOCHS, validation_data=test_gen, validation_steps=num_test_steps, callbacks=[checkpoint])
这是摘要:
Layer (type) Output Shape Param #
=================================================================
input (InputLayer) (None, 45, 50) 0
_________________________________________________________________
encoder_lstm (Bidirectional) (None, 20) 11360
_________________________________________________________________
lambda_1 (Lambda) (512, 20) 0
_________________________________________________________________
repeater (RepeatVector) (512, 45, 20) 0
_________________________________________________________________
decoder_lstm (Bidirectional) (512, 45, 50) 28400
当我更改代码以添加这样的嵌入层时:
inputs = Input(shape=(SEQUENCE_LEN,), name="input")
embedding = Embedding(output_dim=EMBED_SIZE, input_dim=VOCAB_SIZE, input_length=SEQUENCE_LEN, trainable=True)(inputs)
encoded = Bidirectional(LSTM(LATENT_SIZE), merge_mode="sum", name="encoder_lstm")(embedding)
我收到了这个错误:
expected decoder_lstm to have 3 dimensions, but got array with shape (512, 45)
所以我的问题是,我的模型有什么问题?
更新
所以,这个错误是在训练阶段提出的。我还检查了提供给模型的数据的维度,它(61598, 45)
显然没有特征数量或这里,Embed_dim
.
但是为什么在解码器部分会出现这个错误呢?因为在编码器部分我已经包含了嵌入层,所以完全没问题。虽然当它到达解码器部分并且它没有嵌入层,所以它不能正确地将其重塑为三维。
现在问题来了,为什么在类似的代码中没有发生这种情况?这是我的观点,如果我错了,请纠正我。因为 Seq2Seq 代码通常用于翻译、摘要。在这些代码中,解码器部分也有输入(在翻译的情况下,解码器有其他语言输入,因此在解码器部分嵌入的想法是有意义的)。最后,这里我没有单独的输入,这就是为什么我不需要在解码器部分进行任何单独的嵌入。但是,我不知道如何解决这个问题,我只知道为什么会这样:|
更新2
这是我输入模型的数据:
sent_wids = np.zeros((len(parsed_sentences),SEQUENCE_LEN),'int32')
sample_seq_weights = np.zeros((len(parsed_sentences),SEQUENCE_LEN),'float')
for index_sentence in range(len(parsed_sentences)):
temp_sentence = parsed_sentences[index_sentence]
temp_words = nltk.word_tokenize(temp_sentence)
for index_word in range(SEQUENCE_LEN):
if index_word < sent_lens[index_sentence]:
sent_wids[index_sentence,index_word] = lookup_word2id(temp_words[index_word])
else:
sent_wids[index_sentence, index_word] = lookup_word2id('PAD')
def sentence_generator(X,embeddings, batch_size, sample_weights):
while True:
# loop once per epoch
num_recs = X.shape[0]
indices = np.random.permutation(np.arange(num_recs))
# print(embeddings.shape)
num_batches = num_recs // batch_size
for bid in range(num_batches):
sids = indices[bid * batch_size : (bid + 1) * batch_size]
temp_sents = X[sids, :]
Xbatch = embeddings[temp_sents]
weights = sample_weights[sids, :]
yield Xbatch, Xbatch
LATENT_SIZE = 60
train_size = 0.95
split_index = int(math.ceil(len(sent_wids)*train_size))
Xtrain = sent_wids[0:split_index, :]
Xtest = sent_wids[split_index:, :]
train_w = sample_seq_weights[0: split_index, :]
test_w = sample_seq_weights[split_index:, :]
train_gen = sentence_generator(Xtrain, embeddings, BATCH_SIZE,train_w)
test_gen = sentence_generator(Xtest, embeddings , BATCH_SIZE,test_w)
parsed_sentences 是 61598 个被填充的句子。
此外,这是我在模型中作为 Lambda 层的层,我只是在此处添加,以防它有任何影响:
def rev_entropy(x):
def row_entropy(row):
_, _, count = tf.unique_with_counts(row)
count = tf.cast(count,tf.float32)
prob = count / tf.reduce_sum(count)
prob = tf.cast(prob,tf.float32)
rev = -tf.reduce_sum(prob * tf.log(prob))
return rev
nw = tf.reduce_sum(x,axis=1)
rev = tf.map_fn(row_entropy, x)
rev = tf.where(tf.is_nan(rev), tf.zeros_like(rev), rev)
rev = tf.cast(rev, tf.float32)
max_entropy = tf.log(tf.clip_by_value(nw,2,LATENT_SIZE))
concentration = (max_entropy/(1+rev))
new_x = x * (tf.reshape(concentration, [BATCH_SIZE, 1]))
return new_x
任何帮助表示赞赏:)
解决方案
我在 Google colab(TensorFlow 版本1.13.1
)上尝试了以下示例,
from tensorflow.python import keras
import numpy as np
SEQUENCE_LEN = 45
LATENT_SIZE = 20
EMBED_SIZE = 50
VOCAB_SIZE = 100
inputs = keras.layers.Input(shape=(SEQUENCE_LEN,), name="input")
embedding = keras.layers.Embedding(output_dim=EMBED_SIZE, input_dim=VOCAB_SIZE, input_length=SEQUENCE_LEN, trainable=True)(inputs)
encoded = keras.layers.Bidirectional(keras.layers.LSTM(LATENT_SIZE), merge_mode="sum", name="encoder_lstm")(embedding)
decoded = keras.layers.RepeatVector(SEQUENCE_LEN, name="repeater")(encoded)
decoded = keras.layers.Bidirectional(keras.layers.LSTM(EMBED_SIZE, return_sequences=True), merge_mode="sum", name="decoder_lstm")(decoded)
autoencoder = keras.models.Model(inputs, decoded)
autoencoder.compile(optimizer="sgd", loss='mse')
autoencoder.summary()
然后使用一些随机数据训练模型,
x = np.random.randint(0, 90, size=(10, 45))
y = np.random.normal(size=(10, 45, 50))
history = autoencoder.fit(x, y, epochs=NUM_EPOCHS)
该解决方案效果很好。我觉得问题可能是您输入标签/输出以进行MSE
计算的方式。
更新
语境
在最初的问题中,您尝试使用 seq2seq 模型重建词嵌入,其中嵌入是固定的和预训练的。但是,如果您想使用可训练的嵌入层作为模型的一部分,则对这个问题进行建模变得非常困难。因为您没有固定的目标(即目标在优化的每一次迭代中都会发生变化,因为您的嵌入层正在发生变化)。此外,这将导致一个非常不稳定的优化问题,因为目标一直在变化。
修复你的代码
如果您执行以下操作,您应该能够使代码正常工作。这embeddings
是预训练的 GloVe 向量numpy.ndarray
。
def sentence_generator(X, embeddings, batch_size):
while True:
# loop once per epoch
num_recs = X.shape[0]
embed_size = embeddings.shape[1]
indices = np.random.permutation(np.arange(num_recs))
# print(embeddings.shape)
num_batches = num_recs // batch_size
for bid in range(num_batches):
sids = indices[bid * batch_size : (bid + 1) * batch_size]
# Xbatch is a [batch_size, seq_length] array
Xbatch = X[sids, :]
# Creating the Y targets
Xembed = embeddings[Xbatch.reshape(-1),:]
# Ybatch will be [batch_size, seq_length, embed_size] array
Ybatch = Xembed.reshape(batch_size, -1, embed_size)
yield Xbatch, Ybatch
推荐阅读
- javascript - 我试图在注销时清除 AsynStorage
- android - 从后台返回时,Android 的 Firestore 的查询快照侦听器需要很长时间(1 分钟)才能从网络更新
- python - 如何在 Django 中创建数据库模型?
- java - How to Prevent your Andriod app to minimize
- reactjs - React 状态未在 IE 中更新
- wordpress - How to setup gatsby on window 7 32 bit?
- python - 数据帧 loc 返回空数据帧(熊猫)
- shopify - 在shopify中将所有变体添加到产品类别页面的最聪明方法是什么
- wix - 在选项页面上使用单选按钮刻录引导程序项目
- python - Python scikit 学习决策树