首页 > 解决方案 > 从 Python 中的常规字典创建反向字典的目的是什么

问题描述

我正在查看 Word2Vec 的官方 Tensorflow 示例。他们为所有的单词创建了一个字典,然后创建了一个逆向字典,逆向字典主要用于其余代码。

有问题的行:

reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys())) 

完整的代码块

词汇大小 = 50000

def build_dataset(words):
  count = [['UNK', -1]]
  count.extend(collections.Counter(words).most_common(vocabulary_size - 1))
  dictionary = dict()
  for word, _ in count:
    dictionary[word] = len(dictionary)
  data = list()
  unk_count = 0
  for word in words:
    if word in dictionary:
      index = dictionary[word]
    else:
      index = 0  # dictionary['UNK']
      unk_count = unk_count + 1
    data.append(index)
  count[0][1] = unk_count
  reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys())) 
  return data, count, dictionary, reverse_dictionary

data, count, dictionary, reverse_dictionary = build_dataset(words)

正式正式实施。

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/5_word2vec.ipynb

这是 Tensorflow 的官方实现,所以他们这样做一定有充分的理由

标签: pythondictionarytensorflow

解决方案


要构建 list data,该build_dataset()函数需要一个单词到索引的映射。

为了在后续功能中使用,需要索引到单词的映射。

在 Python 中,与大多数语言一样,没有用于内存高效的单射双向映射的结构。因此,您的函数创建并存储两个字典。

请注意,可以使用enumerate字典理解更简单地编写逻辑:

from operator import itemgetter

reverse_dictionary = dict(enumerate(map(itemgetter(0), count)))
dictionary = {v: k for k, v in reverse_dictionary.items()}

推荐阅读