我正在尝试学习一个语言模型来预测一个句子的最后一个单词,给出所有前面的单词使用角语。我想嵌入我的输入使用一个学习的快速文本嵌入模型。
我成功地预处理了我的文本数据,并嵌入了使用text文本。我的训练数据由每个句子40个记号组成。我创建了两个np数组,X和y作为输入,其中y是我想要预测的。
X是形状的( 44317,39,300),44317是例句数,39是每个句子中的记号数,300是单词嵌入的维数。
Y是形状(44317,300),每一个例子都是句子的最后一个标记的嵌入。
我为keras模型编写的代码如下(受这启发)
#importing all the needed tensorflow.keras components
model = Sequential()
model.add(InputLayer((None, 300)))
model.add(LSTM(100, return_sequences=True))
model.add(LSTM(100))
model.add(Dense(100, activation='relu'))
model.add(Dense(300, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X, y, batch_size=128, epochs=20)
model.save('model.h5')然而,我在这个模型上训练时获得的精确度极低(约1.5%)。我认为角光角模型的某些成分我错了,好像我没有嵌入我的输入,增加一个额外的嵌入层,而不是InputLayer,我得到了大约60 %的精度。
我主要怀疑的是我的第二个密集层上的" 300“值,因为我读到这应该与我的单词嵌入模型( 48000)的词汇量相对应,然而,如果我添加了超过300个的内容,我就会得到一个维度错误。所以我知道我做错了什么,但我找不到解决问题的方法。
PS :我也尝试过使用y = to_categorical(y, num_classes=vocab_size),它的词汇表大小与我的单词嵌入相同,并且通过在第二个密度中用相同的值来更改300个,然后它尝试创建一个形状数组(13295100,48120),而不是我所期望的:(44317,48120)。
发布于 2021-11-13 16:29:47
如果您真的想使用来自Fasttext的单词向量,则必须使用权重矩阵和Embedding层将它们合并到您的模型中。嵌入层的目标是将表示句子的每个整数序列映射到对应的300维向量表示:
import gensim.downloader as api
import numpy as np
import tensorflow as tf
def load_doc(filename):
file = open(filename, 'r')
text = file.read()
file.close()
return text
fasttext = api.load("fasttext-wiki-news-subwords-300")
embedding_dim = 300
in_filename = 'data.txt'
doc = load_doc(in_filename)
lines = doc.split('\n')
tokenizer = tf.keras.preprocessing.text.Tokenizer()
tokenizer.fit_on_texts(lines)
text_sequences = tokenizer.texts_to_sequences(lines)
text_sequences = tf.keras.preprocessing.sequence.pad_sequences(text_sequences, padding='post')
vocab_size = len(tokenizer.word_index) + 1
text_sequences = np.array(text_sequences)
X, y = text_sequences[:, :-1], text_sequences[:, -1]
y = tf.keras.utils.to_categorical(y, num_classes=vocab_size)
max_length = X.shape[1]
weight_matrix = np.zeros((vocab_size, embedding_dim))
for word, i in tokenizer.word_index.items():
try:
embedding_vector = fasttext[word]
weight_matrix[i] = embedding_vector
except KeyError:
weight_matrix[i] = np.random.uniform(-5, 5, embedding_dim)
sentence_input = tf.keras.layers.Input(shape=(max_length,))
x = tf.keras.layers.Embedding(vocab_size, embedding_dim, weights=[weight_matrix],
input_length=max_length)(sentence_input)
x = tf.keras.layers.LSTM(100, return_sequences=True)(x)
x = tf.keras.layers.LSTM(100)(x)
x = tf.keras.layers.Dense(100, activation='relu')(x)
output = tf.keras.layers.Dense(vocab_size, activation='softmax')(x)
model = tf.keras.Model(sentence_input, output)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X, y, batch_size=5, epochs=20) 请注意,我正在使用您链接的教程中的数据集和预处理步骤。
发布于 2021-11-13 15:31:30
在下一个句子预测任务中,RNN模型的训练是非常困难的。LSTM/GRU没有足够的资源从文本中提取足够的特征。
解决问题的方法有两种:
https://stackoverflow.com/questions/69955550
复制相似问题