# 腾讯词向量实战：通过Annoy进行索引和快速查询

Annoy (Approximate Nearest Neighbors Oh Yeah) is a C++ library with Python bindings to search for points in space that are close to a given query point. It also creates large read-only file-based data structures that are mmapped into memory so that many processes may share the same data.


In [1]: import random

In [2]: from annoy import AnnoyIndex

# f是向量维度
In [3]: f = 20

In [4]: t = AnnoyIndex(f)

In [5]: for i in xrange(100):
...:     v = [random.gauss(0, 1) for z in xrange(f)]
...:

In [6]: t.build(10)
Out[6]: True

In [7]: t.save('test.ann.index')
Out[7]: True

In [8]: print(t.get_nns_by_item(0, 10))
[0, 45, 16, 17, 61, 24, 48, 20, 29, 84]

# 此处测试从硬盘盘索引加载
In [10]: u = AnnoyIndex(f)

Out[11]: True

In [12]: print(u.get_nns_by_item(0, 10))
[0, 45, 16, 17, 61, 24, 48, 20, 29, 84]

There are some other libraries to do nearest neighbor search. Annoy is almost as fast as the fastest libraries, (see below), but there is actually another feature that really sets Annoy apart: it has the ability to use static files as indexes. In particular, this means you can share index across processes. Annoy also decouples creating indexes from loading them, so you can pass around indexes as files and map them into memory quickly. Another nice thing of Annoy is that it tries to minimize memory footprint so the indexes are quite small.
Why is this useful? If you want to find nearest neighbors and you have many CPU's, you only need to build the index once. You can also pass around and distribute static files to use in production environment, in Hadoop jobs, etc. Any process will be able to load (mmap) the index into memory and will be able to do lookups immediately.
We use it at Spotify for music recommendations. After running matrix factorization algorithms, every user/item can be represented as a vector in f-dimensional space. This library helps us search for similar users/items. We have many millions of tracks in a high-dimensional space, so memory usage is a prime concern.
Annoy was built by Erik Bernhardsson in a couple of afternoons during Hack Week.


Annoy还有很多优点（Summary of features）：

• Euclidean distanceManhattan distancecosine distanceHamming distance , or  Dot (Inner) Product distance
• Cosine distance is equivalent to Euclidean distance of normalized vectors = sqrt(2-2*cos(u, v))
• Works better if you don’t have too many dimensions (like <100) but seems to perform surprisingly well even up to 1,000 dimensions
• Small memory usage
• Lets you share memory between multiple processes
• Index creation is separate from lookup (in particular you can not add more items once the tree has been created)
• Native Python support, tested with 2.7, 3.6, and 3.7.
• Build index on disk to enable indexing big datasets that won’t fit into memory (contributed by  Rene Hollander )

a.add_item(i, v) adds item i (any nonnegative integer) with vector v. Note that it will allocate memory for max(i)+1 items.

1 vec

2 vec

In [15]: from gensim.models import KeyedVectors

# 此处加载时间略长，加载完毕后大概使用了12G内存，后续使用过程中内存还在增长，如果测试，请用大一些内存的机器
...: eEmbedding.txt', binary=False)

# 构建一份词汇ID映射表，并以json格式离线保存一份（这个方便以后离线直接加载annoy索引时使用）
In [17]: import json

In [18]: from collections import OrderedDict

In [19]: word_index = OrderedDict()

In [21]: for counter, key in enumerate(tc_wv_model.vocab.keys()):
...:     word_index[key] = counter
...:

In [22]: with open('tc_word_index.json', 'w') as fp:
...:     json.dump(word_index, fp)
...:

# 开始基于腾讯词向量构建Annoy索引，腾讯词向量大概是882万条
In [23]: from annoy import AnnoyIndex

# 腾讯词向量的维度是200
In [24]: tc_index = AnnoyIndex(200)

In [25]: i = 0

In [27]: tc_index = AnnoyIndex(200)

In [28]: for key in tc_wv_model.vocab.keys():
...:     v = tc_wv_model[key]
...:     i += 1
...:

# 这个构建时间也比较长，另外n_trees这个参数很关键，官方文档是这样说的：
# n_trees is provided during build time and affects the build time and the index size.
# A larger value will give more accurate results, but larger indexes.
# 这里首次使用没啥经验，按文档里的是10设置，到此整个流程的内存占用大概是30G左右
In [29]: tc_index.build(10)

Out[29]: True

# 可以将这份index存储到硬盘上，再次单独加载时，内存占用大概在2G左右
In [30]: tc_index.save('tc_index_build10.index')
Out[30]: True

# 准备一个反向id==>word映射词表
In [32]: reverse_word_index = dict([(value, key) for (key, value) in word_index.item
...: s()])

# 然后测试一下Annoy，自然语言处理和AINLP公众号后台的结果基本一致
# 感兴趣的同学可以关注AINLP公众号，查询：相似词 自然语言处理
In [33]: for item in tc_index.get_nns_by_item(word_index[u'自然语言处理'], 11):
...:     print(reverse_word_index[item])
...:

# 不过英文词的结果好像有点不同
In [34]: for item in tc_index10.get_nns_by_item(word_index[u'nlp'], 11):
...:     print(reverse_word_index[item])
...:

nlp

nlp应用

Approximate Nearest Neighbors in C++/Python optimized for memory usage and loading/saving to disk

topk相似度性能比较（kd-tree、kd-ball、faiss、annoy、线性搜索）

Similarity Queries using Annoy Tutorial