【发布时间】:2017-12-20 03:42:51
【问题描述】:
我很好奇,每当遇到预训练词汇表中未知的单词时,如何添加一个正常随机化的 300 维向量(元素类型 = tf.float32)。我正在使用预训练的 GloVe 词嵌入,但在某些情况下,我意识到我遇到了未知词,我想为这个新发现的未知词创建一个正常随机化的词向量。
问题在于,在我当前的设置中,我使用tf.contrib.lookup.index_table_from_tensor 根据已知词汇将单词转换为整数。这个函数可以创建新的标记并对一些预定义的词汇表外的单词进行哈希处理,但是我的embed 将不包含这个新的未知哈希值的嵌入。我不确定是否可以简单地将随机嵌入附加到 embed 列表的末尾。
我也想以一种有效的方式来做这件事,所以预先构建的 tensorflow 函数或涉及 tensorflow 函数的方法可能是最有效的。我定义了预先知道的特殊标记,例如句尾标记和默认未知作为空字符串(“在索引 0 处),但这在学习各种不同的未知单词的能力方面受到限制。我目前使用 tf.nn.embedding_lookup()作为最后的嵌入步骤。
我希望能够为训练数据中的每个未知单词添加新的随机 300d 向量,并且我还希望为训练中可能遇到的任何在训练中未见的未知标记添加预制的随机词向量测试。最有效的方法是什么?
def embed_tensor(string_tensor, trainable=True):
"""
Convert List of strings into list of indicies then into 300d vectors
"""
# ordered lists of vocab and corresponding (by index) 300d vector
vocab, embed = load_pretrained_glove()
# Set up tensorflow look up from string word to unique integer
vocab_lookup = tf.contrib.lookup.index_table_from_tensor(
mapping=tf.constant(vocab),
default_value = 0)
string_tensor = vocab_lookup.lookup(string_tensor)
# define the word embedding
embedding_init = tf.Variable(tf.constant(np.asarray(embed),
dtype=tf.float32),
trainable=trainable,
name="embed_init")
# return the word embedded version of the sentence (300d vectors/word)
return tf.nn.embedding_lookup(embedding_init, string_tensor)
【问题讨论】:
标签: python tensorflow nlp