python - 从 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 的官方实现,所以他们这样做一定有充分的理由
解决方案
要构建 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()}
推荐阅读
- go - 获取包中的结构以进行 go-gorm 迁移
- sql - 针对红移数据的sql查询
- c# - 如何显示包含搜索词的长文本部分
- xml - 如果不满足匹配条件,XSLT 创建空文档
- reactjs - 如何在 Redux 异步中使用 SQLite?
- python-3.x - Pyinstaller 应用程序不适用于文件输入,给出 RuntimeError: input(): lost sys.stdin
- ide - 有什么方法可以从 Talend Studio 更新 talend 补丁?
- javascript - 无法访问对象中的特定键
- mongodb - 运行 mongo 映像时出错 - docker-entrypoint.sh:第 381 行
- java - 有什么方法可以让 https 只在 Tomcat 中选择应用程序?