lib/vsm: add README
[nit.git] / lib / vsm / README.md
1 # Vector Space Model
2
3 Vector Space Model (VSM) is an algebraic model for representing text documents
4 (and any objects, in general) as vectors of identifiers, such as, for example,
5 index terms.
6
7 It is used in information filtering, information retrieval, indexing and
8 relevancy rankings.
9
10 The `vsm` package provides the following features:
11 * Vector comparison with cosine similarity.
12 * Vector indexing and matching with tf * idf.
13 * File indexing and matching to free text queries.
14
15 ## Vectors
16
17 With VSM, documents are represented by a n-dimensions vector.
18 Each dimension represent an attribute of the document or object.
19
20 For text document, the count of each term found in the document if often used to
21 build vectors.
22
23 ### Creating a vector
24
25 ~~~
26 var vector = new Vector
27 vector["term1"] = 2.0
28 vector["term2"] = 1.0
29 assert vector["term1"] == 2.0
30 assert vector["term2"] == 1.0
31 assert vector.norm.is_approx(2.236, 0.001)
32 ~~~
33
34 ### Comparing vectors
35
36 ~~~
37 var v1 = new Vector
38 v1["term1"] = 1.0
39 v1["term2"] = 2.0
40
41 var v2 = new Vector
42 v2["term2"] = 1.0
43 v2["term3"] = 3.0
44
45 var query = new Vector
46 query["term2"] = 1.0
47
48 var s1 = query.cosine_similarity(v1)
49 var s2 = query.cosine_similarity(v2)
50 assert s1 > s2
51 ~~~
52
53 ## VSMIndex
54
55 VSMIndex is a Document index based on VSM.
56
57 Using VSMIndex you can index documents associated with their vector.
58 Documents can then be matched to query vectors.
59
60 This represents a minimalistic search engine.
61
62 ~~~
63 var index = new VSMIndex
64
65 var d1 = new Document("Doc 1", "/uri/1", v1)
66 index.index_document(d1)
67
68 var d2 = new Document("Doc 2", "/uri/2", v2)
69 index.index_document(d2)
70
71 assert index.documents.length == 2
72
73 query = new Vector
74 query["term1"] = 1.0
75
76 var matches = index.match_vector(query)
77 assert matches.first.document == d1
78 ~~~
79
80 ## StringIndex
81
82 The StringIndex provides usefull services to index and match strings.
83
84 ~~~
85 index = new StringIndex
86
87 d1 = index.index_string("Doc 1", "/uri/1", "this is a sample")
88 d2 = index.index_string("Doc 2", "/uri/2", "this and this is another example")
89 assert index.documents.length == 2
90
91 matches = index.match_string("this sample")
92 assert matches.first.document == d1
93 ~~~
94
95 ## FileIndex
96
97 The FileIndex is a StringIndex able to index and retrieve files.
98
99 ~~~nit
100 index = new FileIndex
101
102 index.index_files(["/path/to/doc/1", "/path/to/doc/2"])
103 ~~~