-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathir.py
More file actions
420 lines (347 loc) · 13.7 KB
/
ir.py
File metadata and controls
420 lines (347 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
from collections import Counter as C
from collections import defaultdict as D
from itertools import product as P
from queryStemmer import porter
import math,sys,pickle,os,tkMessageBox
from nltk.stem.porter import PorterStemmer as PS
from Tkinter import *
class Doc:
def __repr__(self):
return 'The document '+str(self.doc_id)
def __init__(self,doc_id,doc_name):
self.doc_file = doc_id+'.txt'
self.doc_id = int(doc_id)
self.doc_name = doc_name
def Jaccard(A , B):
return float(len(set(A).intersection(set(B))))/len(set(A).union(set(B)))
class Query:
def __repr__(self):
return 'The query'
def __init__(self, query):
self.string = query
self.vocab = C()
self.stemmer = PS()
self.stem_query = self.stemmed(query)
#l = self.stem_query.split()
l = query.split()
for word in l:
self.vocab.update([word])
self.query_length = len(l)
def stemmed(self, query):
words = query.split()
stemmed_query = ''
for word in words:
stemmed_query += ' '+str(self.stemmer.stem(word))
return stemmed_query
def term_frequency(self, word):
return self.vocab[word]
def log_term_frequency(self, word):
tf = self.term_frequency(word)
return 1 + math.log10(tf) if tf>0 else 0
def tf_idf_score(self, word):
return self.log_term_frequency(word)
def normalization(self):
return math.sqrt(sum(map(lambda x: x**2, [self.log_term_frequency(word) for word in self.vocab])))
class DocStemmer:
def __repr__(self):
return 'The normalization of docs'
def __init__(self, query):
self.docs = docs
self.docs_length = len(docs)
self.normalize()
self.stemmer = PS()
def normalize(self):
for doc in self.docs:
with open(sys.path[0]+'\\reuters\\training\\'+doc.doc_file,'w') as f:
lines = f.read()
words = lines.split()
new_words =[]
for word in words:
new_words.append(str(self.stemmer.stem(word)))
f.write(' '.join(new_words))
class Dictionary:
def __repr__(self):
return 'The dictionary'
def __init__(self, docs):
self.dictionary = {}
self.vocabulary = Vocab(docs)
self.k_index = K_gram_index(self.vocabulary , 2)
self.docs = docs
self.build_dictionary()
def build_dictionary(self):
for word in self.vocabulary.vocab:
self.dictionary[word] = set()
for doc in self.docs:
with open(sys.path[0]+'\\reuters\\training\\'+doc.doc_file,'r') as f:
lines = f.read()
words = lines.split()
for word in words:
self.dictionary[word].add(doc.doc_id)
def intersection(self, word1 ,word2):
if word1 in self.dictionary and word2 in self.dictionary :
return self.dictionary[word1].intersection(self.dictionary[word2])
return set()
def union(self, word1 ,word2):
if word1 in self.dictionary and word2 in self.dictionary :
return self.dictionary[word1].union(self.dictionary[word2])
elif word1 in self.dictionary :
return self.dictionary[word1]
elif word2 in self.dictionary :
return self.dictionary[word2]
return set()
def difference(self, word1 ,word2):
if word1 in self.dictionary and word2 in self.dictionary :
return self.dictionary[word1].difference(self.dictionary[word2])
elif word1 in self.dictionary :
return self.dictionary[word1]
return set()
def symmetric_difference(self, word1 ,word2):
if word1 in self.dictionary and word2 in self.dictionary :
return self.dictionary[word1].symmetric_difference(self.dictionary[word2])
elif word1 in self.dictionary :
return self.dictionary[word1]
elif word2 in self.dictionary :
return self.dictionary[word2]
return set()
class K_gram_index:
def __repr__(self):
return 'The k-gram word index'
def __init__(self , vocab, sublen):
self.k_index = {}
for word in vocab.vocab:
length = len(word)
for start in range(length-sublen):
substr = word[start : start+sublen]
if substr not in self.k_index :
self.k_index[substr] = set()
self.k_index[substr].add(word)
def intersection(self, substr1 , substr2):
if substr1 in self.k_index and substr2 in self.k_index:
return self.k_index[substr1].intersection(self.k_index[substr2])
return set()
def union(self, substr1 , substr2):
if substr1 in self.k_index and substr2 in self.k_index:
return self.k_index[substr1].union(self.k_index[substr2])
elif substr1 in self.k_index :
return self.k_index[substr1]
elif substr2 in self.k_index :
return self.k_index[substr2]
return set()
def difference(self, substr1 , substr2):
if substr1 in self.k_index and substr2 in self.k_index:
return self.k_index[substr1].difference(self.k_index[substr2])
elif substr1 in self.k_index :
return self.k_index[substr1]
return set()
def symmetric_difference(self, substr1 , substr2):
if substr1 in self.k_index and substr2 in self.k_index:
return self.k_index[substr1].symmetric_difference(self.k_index[substr2])
elif substr1 in self.k_index :
return self.k_index[substr1]
elif substr2 in self.k_index :
return self.k_index[substr2]
return set()
class Term_Document_Matrix:
def __repr__(self):
return 'The term document index'
def __init__(self,docs):
self.index = {}
self.vocabulary = Vocab(docs)
self.docs = docs
self.docs_length = len(docs)
self.lengths = {}
self.build_index()
self.build_lengths()
def build_index(self):
for word in self.vocabulary.vocab :
self.index[word] = C()
for doc in self.docs:
with open(sys.path[0]+'\\reuters\\training-stemmed\\'+doc.doc_file,'r') as f:
lines = f.read()
words = lines.split()
for word in words:
self.index[word].update([doc.doc_id])
def build_lengths(self):
self.lengths = {doc.doc_id : self.normalization(doc.doc_id) for doc in self.docs}
print "index done"
def term_frequency(self, word, document):
return self.index[word][document]
def log_term_frequency(self, word, document):
tf = self.term_frequency(word, document)
return 1 + math.log10(self.index[word][document]) if tf > 0 else 0
def inverse_document_frequency(self, word):
df = len(self.index[word])
return math.log10(float(self.docs_length)/df)
def tf_idf_score(self, word, document):
return self.log_term_frequency(word, document) * self.inverse_document_frequency(word)
def normalization(self, document):
return math.sqrt(sum(map(lambda x: x**2, [self.tf_idf_score(word, document) for word in self.vocabulary.vocab])))
class Vocab:
def __repr__(self):
return 'The vocabulary'
def __init__(self,docs):
self.vocab = C()
self.docs = docs
self.build_vocab()
self.vocab_size = len(self.vocab.keys())
self.docs_length = len(docs)
def build_vocab(self):
for doc in self.docs:
with open(sys.path[0]+'\\reuters\\training-stemmed\\'+doc.doc_file,'r') as f:
lines = f.read()
words = lines.split()
for word in words:
self.vocab.update([word])
print "vocab done"
class VectorSpaceModel:
def __repr__(self):
return "The vector space retrieval model"
def __init__(self, index):
self.index = index
self.docs = self.index.docs
self.scores = {}
def cos_similarity(self, query):
number_of_terms = len(query.vocab)
scores = {doc.doc_id : 0 for doc in self.docs}
terms = query.vocab.keys()
for word in terms:
weight_term_query = query.tf_idf_score(word)
if word not in self.index.vocabulary.vocab:
continue
termDocs = self.index.index[word]
for doc_id in termDocs:
weight_term_doc = self.index.tf_idf_score(word, doc_id)
scores[doc_id] += weight_term_doc * weight_term_query
docScores = sorted(scores.iteritems() , key=lambda x: x[1], reverse = True)
# print docScores[:5]
for doc in self.docs:
scores[doc.doc_id] /= self.index.lengths[doc.doc_id]
docScores = sorted(scores.iteritems() , key=lambda x: x[1], reverse = True)
print docScores[:5]
return docScores
class ProbabilisticRetrievalModel:
def __repr__(self):
return "The probablisic retrieval model - Probabilistic Indexing"
def __init__(self, vocab, query):
self.vocabulary = vocab
self.docs = vocab.docs
self.query = query
self.vocab_size = vocab.vocab_size
self.doc_prob = {doc.doc_id : 0 for doc in vocab.docs}
self.query_prob = {query : 0 for query in P([0,1],repeat=query.query_length)}
def estimate_rank(self, query):
for target in self.targets:
self.targ_prob[target]=float(self.numbers[target])/self.total
self.word_prob[target]={}
for word in self.vocab.keys():
try:
self.word_prob[target][word] = float(self.vocabs[target][word]+1)/(self.count[target]+self.vocabsize)
except KeyError:
self.word_prob[target][word] = float(1)/(self.count[target]+self.vocabsize)
print len(self.word_prob[target])
class Search:
def __init__(self,vocabulary):
self.vocab = vocabulary.vocab
self.vocabsize = vocabulary.vocab_size
self.word_prob = {}
self.build_search()
def build_search(self):
for target in self.targets:
self.targ_prob[target]=float(self.numbers[target])/self.total
self.word_prob[target]={}
for word in self.vocab.keys():
try:
self.word_prob[target][word] = float(self.vocabs[target][word]+1)/(self.count[target]+self.vocabsize)
except KeyError:
self.word_prob[target][word] = float(1)/(self.count[target]+self.vocabsize)
print len(self.word_prob[target])
def test_search(self,doc):
with open(doc,'r') as f:
w = f.read().split()
output = None
final = -1*sys.maxint
for target in self.targets:
prob = 0
for word in w:
if word in self.vocab.keys():
print target , word , self.word_prob[target][word],prob
prob += math.log(self.word_prob[target][word])
prob += math.log(self.targ_prob[target])
#print prob
if prob > final:
output = target
final = prob
print output
class Application(Frame):
def get_docs(self):
query_string = self.QUERY.get()
q = Query(query_string)
print query_string
with(open(sys.path[0]+'\\reuters\\training-stemmed\\'+str(v.cos_similarity(q)[0][0])+'.txt','r')) as g:
print g.read()
def createWidgets(self):
self.LABEL= Label(self)
self.LABEL["text"]= "Query"
self.LABEL.pack({"side": "left"})
self.QUERY = Entry(self)
self.QUERY["bd"] = 5
self.QUERY.pack({"side": "left"})
self.SEARCH = Button(self)
self.SEARCH["text"] = "Search",
self.SEARCH["command"] = self.get_docs
self.SEARCH.pack({"side": "top"})
self.QUIT = Button(self)
self.QUIT["text"] = "QUIT"
self.QUIT["fg"] = "red"
self.QUIT["command"] = self.quit
self.QUIT.pack({"side": "bottom"})
def __init__(self, master=None):
Frame.__init__(self, master)
self.query_string = ""
self.pack()
self.createWidgets()
#q = Query("lion is the king")
#print porter(q.string)
#print q.term_frequency('the')
#print q.normalization()
g = open(sys.path[0]+'\\reuters\\documents.txt','r')
documents = []
for doc in g.readlines():
documents.append(Doc(*doc.split()[:2]))
f = sys.path[0]+'\\reuters\\Index-new'
if os.path.exists(f):
Index = pickle.load(open(f,'rb'))
else:
Index = Term_Document_Matrix(documents)
pickle.dump(Index, open(f,'wb'))
print "Index built"
#print Index.inverse_document_frequency('the')
#print Index.term_frequency('the',1)
#print Index.log_term_frequency('the',1)
#print Index.normalization(1)
#Diction = Dictionary(documents)
#print Diction.dictionary['the']
#print Diction.k_index.k_index['th']
#print Diction.k_index.symmetric_difference('th','he')
#print Diction.intersection('the','help')
v = VectorSpaceModel(Index)
#print v.cosine_similarity(q)
#v.cos_similarity(q)
#p = ProbabilisticRetrievalModel(Index,Vocab(docs))
##while True:
## q = Query(str(raw_input()))
## with(open(sys.path[0]+'\\reuters\\training-stemmed\\'+str(v.cos_similarity(q)[0][0])+'.txt','r')) as g:
## print g.read()
##
##while True:
## q = Query(str(raw_input("String :")))
## docs = v.cos_similarity(q)
## print docs[:5]
root = Tk()
app = Application(master=root)
app.mainloop()
try:
tkMessageBox.showinfo("BYE", "Thanks for using")
root.destroy()
except Exception:
pass