-
Notifications
You must be signed in to change notification settings - Fork 0
/
RetrievalModels.py
224 lines (197 loc) · 7.58 KB
/
RetrievalModels.py
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
# Importing necessary libraries
import math
import os
import re
import string
from bs4 import BeautifulSoup
import sys
import ast
# file name which contains list of queries
LIST_OF_QUERY_FILE_NAME='CASM-Files/cacm.query.txt'
# output file name storing the top 100 results of Smoothed Query Likelihood Model score for all queries
TOP_100_RESULT_QueryLikelihood='Top_100_Query_Result_QueryLikelihoodModel'
# text file of number of unigrams
INVERTED_INDEX=['Indexing/IndexTextFiles/unigram-no_stopping_or_stemming-index.txt',
'Indexing/IndexTextFiles/unigram-withStopping-index.txt',
'Indexing/IndexTextFiles/unigram-withStemming-index.txt']
# text file of number of tokens per document in corpus
NUM_OF_TOKEN_PER_DOC=['Indexing/IndexTextFiles/NoTokensPerDoc-no_stopping_or_stemming.txt',
'Indexing/IndexTextFiles/NoTokensPerDoc-withStopping.txt',
'Indexing/IndexTextFiles/NoTokensPerDoc-withStemming.txt']
# path of list of relevant document files
RELEVANT_DOCS='CASM-Files/cacm.rel.txt'
# list of stemmed queries
STEMMED_QUERIES='CASM-Files/cacm_stem.query.txt'
# Coefficient to control probability of unseen words
COEFFICIENT=0.35
# directory for output files
DIR_OUTPUT='Retrieval/OutputFiles'
# calculate Smoothed Query Likelihood score of each doc that has the query term
# input : inverted index of unigram, query term frequency dictionary
# output : a dictionary of docids storing the score
def calculateSMQL(invertedIndex,queryTermFreq,noOfTokenPerDoc):
docScore={}
# size of collection
noOfTokenPerDoc=ast.literal_eval(noOfTokenPerDoc)
invertedIndex = ast.literal_eval(invertedIndex)
print("noOfTokenPerDoc: ",type(noOfTokenPerDoc))
C=sum([noOfTokenPerDoc[doc] for doc in noOfTokenPerDoc])
print("queryTermFreq: ",queryTermFreq)
print("invertedIndex: ", invertedIndex)
for qTerm in queryTermFreq:
if qTerm not in invertedIndex:
continue
invertedList=invertedIndex[qTerm]
print("invertedList: ",invertedList)
cq = sum([int(doc[1]) for doc in invertedList])
print("cq: ",cq)
for doc in invertedList:
# frequency of query term in doc
fq=int(doc[1])
# document size
docSize=noOfTokenPerDoc[doc[0]]
unseenPart=COEFFICIENT* cq / float(C)
seenPart=(1-COEFFICIENT)*fq/float(docSize)
if doc not in docScore:
docScore[doc]=math.log(seenPart+unseenPart)
else:
docScore[doc]+=math.log(seenPart+unseenPart)
return docScore
# fetch relevant docIDs for the given query id
def fetchRelevantDocIds(queryID):
relDocIds=[]
fName=RELEVANT_DOCS
relFile=open(fName,'r')
for rec in relFile.readlines():
record=rec.split()
print("")
print("record: ",record)
print(type(queryID))
if record[0]==queryID:
relDocIds.append(record[2])
print(relDocIds)
return relDocIds
# generate the term frequency of each query term.
# input : query
# output : a dictionary of all terms and their frequency
def generateQueryTermsFreqDict(query):
queryTermFreq={}
for qTerm in query.split():
if qTerm in queryTermFreq:
queryTermFreq[qTerm]+=1
else:
queryTermFreq[qTerm]=1
return queryTermFreq
# fetch the inverted index of unigram from the file
# input : file of the index
# output : inverted index of the unigrams
def fetchInvertedIndex(invertedIndexFile):
f = open(invertedIndexFile,'rb')
invertedIndex=str(f.read(),'UTF-8')
return invertedIndex
# fetch the number of tokens per document from the file
# generated in previous assignment
# output : number of tokens per document
def fetchNoOfTokensPerDocDic(noOfTokensFile):
f = open(noOfTokensFile, 'rb')
noOfTokensPerDoc = str(f.read(),'UTF-8')
return noOfTokensPerDoc
# write the result
def writeResultToFile(docScore,qID,model,outputFileName):
fileModel=open(outputFileName,'a')
fileModel.write("\nQuery Q"+str(qID)+"\n\n")
sortedDocScore=sorted(docScore,reverse=True)
count=0
for doc,score in sortedDocScore:
fileModel.write(doc+" " + str(score) +"\n")
count+=1
if count+1 > 100:
break
fileModel.close()
def fetchQueryMap():
queryMap={}
f=open(LIST_OF_QUERY_FILE_NAME,'r')
content =f.read()
content='<DATA>'+content+'</DATA>'
soup = BeautifulSoup(content, 'xml')
docList= soup.findAll('DOC')
for doc in docList:
child=doc.findChild()
qID=int(child.get_text().encode('utf-8'))
child.decompose()
text = doc.get_text().encode('utf-8')
caseFoldedtext= caseFold(text)
tokens = generateTokens(caseFoldedtext)
refinedText=removePunctuation(tokens)
queryMap[qID]=refinedText
return queryMap
f.close()
# method to case-fold the text provided
# Given: plain text
# Return: case folded plain text
def caseFold(plainText):
return plainText.lower()
# method to remove punctuation from the text provided
# Given: plain text
# Return: plain text with removed punctuation
def removePunctuation(tokens):
newList=[]
for tok in tokens:
#print(tok)
matchNum=re.compile(r'^[\-]?[0-9]*\.?[0-9]+$')
if not matchNum.match(tok):
tok=re.sub(r'[^a-zA-Z0-9\--]','',tok)
newList.append(tok)
return (' ').join(newList)
# method to generate tokens from plain text
# Given: plain text
# Return: list of tokens
def generateTokens(plainText):
print(plainText)
return list(filter(re.compile('[a-zA-Z0-9_]').search,str(plainText,'UTF-8').split()))
# fetch stemmed queries
def fetchStemmedQueries():
queryMap={}
f=open(STEMMED_QUERIES,'r')
i=1
for query in f.readlines():
queryMap[i]=query
i+=1
f.close()
return queryMap
def selectRetrievalModel1(ch,invertedIndexFile,noOfTokensFile):
print("Smoothed Query Likelihood retrieval model")
model="Smoothed Query Likelihood Model"
outputFileName=DIR_OUTPUT+"/"+TOP_100_RESULT_QueryLikelihood+"_"+str(ch)+".txt"
if not os.path.exists(DIR_OUTPUT):
os.makedirs(DIR_OUTPUT)
if os.path.exists(outputFileName):
os.remove(outputFileName)
fileModel=open(outputFileName,'a')
topic=" Top 100 Query Results Using "+model+" "
hashLen=90-len(topic)
hashLen=hashLen//2
filler="#"*hashLen+topic+"#"*hashLen
if len(filler)<90:
filler+="#"
fileModel.write("#"*90+"\n"+filler+"\n"+"#"*90+"\n\n")
fileModel.close()
print("Loading inverted index from text file....")
invertedIndex = fetchInvertedIndex(invertedIndexFile)
print("Loading number of tokens per document from text file....")
noOfTokenPerDoc = fetchNoOfTokensPerDocDic(noOfTokensFile)
queryMap=fetchQueryMap()
queryList=sorted(queryMap)
for queryID in queryList:
print("\nQuery --> "+str(queryID)+": " +queryMap[queryID])
print("Generating query term frequency....")
queryTermFreq=generateQueryTermsFreqDict(queryMap[queryID])
print("Calculating "+model+" score for documents for the current query....")
docScore=calculateSMQL(invertedIndex,queryTermFreq,noOfTokenPerDoc)
print(" ")
print(docScore)
print("Writing the top 100 results in the file....")
writeResultToFile(docScore,queryID,model,outputFileName)
if __name__=='__main__':
ch=int(input("Enter your choice 0-nothing , 1-stopping , 2-stemming: "))
selectRetrievalModel1(ch,INVERTED_INDEX[ch],NUM_OF_TOKEN_PER_DOC[ch])