-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsoda.java
More file actions
324 lines (254 loc) · 8.43 KB
/
soda.java
File metadata and controls
324 lines (254 loc) · 8.43 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
import Jama.*;
import java.util.Map;
import java.util.HashMap;
import java.io.*;
import java.util.*;
class soda {
private int numberDocs;
private InvertedIndex invIndex;
private HashMap<String,Integer> documentsToID;
private HashMap<String,Integer> tokensToID;
private double[][] termDocsMatrix;
private Matrix A;
private Matrix U;
private Matrix S;
private Matrix Vt;
private Matrix Uk; //reduced U to k columns
private Matrix Sk; //reduced S to k by k
private Matrix Vtk; //reduced V' to k rows
private Matrix SkInverseUkTranspose;
private int k;
private String[] queryTerms;
private Matrix queryVectorMatrix;
private Matrix queryK;
public soda(String[] queries, String index_dir)
{
invIndex = new InvertedIndex();
invIndex.constructInvertedIndexFromFile(index_dir);
numberDocs = invIndex.corpusDocs.size();
documentsToID = new HashMap<String,Integer>();
for (int i = 1; i <= numberDocs; i++)
{
String docName = "doc"+i+".txt";
documentsToID.put(docName,i-1);
}
tokensToID = new HashMap<String,Integer>();
termDocsMatrix = new double[invIndex.invertedIndexTFs.size()][numberDocs];
queryTerms = queries;
}
private void printMatrix(double[][] grid)
{
for(int r=0; r<grid.length; r++)
{
for(int c=0; c<grid[r].length; c++)
{
System.out.print(((double)Math.round(grid[r][c] * 1000) / 1000) + " ");
}
System.out.println();
}
}
private void invertedIndexToDocTermMatrix()
{
int row = 0;
//for each term in the inverted index
for (Map.Entry<String, HashMap<String, Integer>> entry : invIndex.invertedIndexTFs.entrySet())
{
String term = entry.getKey();
HashMap<String, Integer> docTFs = entry.getValue();
double idf = invIndex.termIDFs.get(term);
tokensToID.put(term,row);
// for each document
for (Map.Entry<String, Integer> entry1 : docTFs.entrySet())
{
String docName = entry1.getKey();
int termFreq = entry1.getValue();
double tfIdf = (double)termFreq*idf;
int docID = documentsToID.get(docName);
termDocsMatrix[row][docID] = tfIdf;
}
row++;
}
}
private void reduceSVDMatrices(int kReductions, SingularValueDecomposition svd)
{
if (kReductions <= svd.getS().getRowDimension() && kReductions > 0)
{
Uk = svd.getU().copy().getMatrix(0,svd.getU().getRowDimension()-1,0,kReductions-1);
Sk = svd.getS().copy().getMatrix(0,kReductions-1,0,kReductions-1);
Vtk = svd.getV().copy().getMatrix(0,kReductions-1,0,svd.getV().getColumnDimension()-1);
}
}
private void createQueryVector()
{
double[][] queryVector = new double[invIndex.invertedIndexTFs.size()][1];
//Tokenize the raw query
String queryAsLine = "";
for (String query : queryTerms)
{
queryAsLine = queryAsLine + " " + query;
}
ArrayList<String> lineForTokenizer = new ArrayList<String>();
lineForTokenizer.add(queryAsLine);
Tokenizer tokenizer = new Tokenizer();
HashMap<String, Integer> queryTFs = tokenizer.tokenize(lineForTokenizer);
for (Map.Entry<String, Integer> entry : queryTFs.entrySet())
{
String token = entry.getKey();
int termFreq = entry.getValue();
double idf;
if (invIndex.invertedIndexTFs.containsKey(token))
{
idf = invIndex.termIDFs.get(token);
} else {
idf = Math.log(documentsToID.size());
}
if (tokensToID.containsKey(token))
{
queryVector[tokensToID.get(token)][0] = termFreq*idf;
}
}
queryVectorMatrix = new Matrix(queryVector);
}
private double cosineSimilarity(Matrix docVectorMatrix)
{
int docColumns = docVectorMatrix.getColumnDimension();
int docRows = docVectorMatrix.getRowDimension();
double docNorm = 0;
double queryNorm = 0;
double dotProduct = 0;
for (int i = 0; i < docRows; i++)
{
dotProduct += docVectorMatrix.get(i,0)*queryK.get(i,0);
docNorm += docVectorMatrix.get(i,0)*docVectorMatrix.get(i,0);
queryNorm += queryK.get(i,0)*queryK.get(i,0);
}
double cosineSim = dotProduct/(Math.sqrt(docNorm)*Math.sqrt(queryNorm));
return cosineSim;
}
private void querySimilarityToDocs()
{
PriorityQueue<String> queryDocCosineSimSorted = new PriorityQueue<String>(documentsToID.size(), new DoubleInStringComparator());
for (Map.Entry<String, Integer> entry : documentsToID.entrySet())
{
String docName = entry.getKey();
int docID = entry.getValue();
Matrix docVectorMatrix = SkInverseUkTranspose.times(A.getMatrix(0,A.getRowDimension()-1,docID,docID));
//Matrix docVectorMatrix = Sk.times(Vtk.getMatrix(0,Vtk.getRowDimension()-1,docID,docID));
double cosineSim = cosineSimilarity(docVectorMatrix);
String outputString = docName+","+cosineSim;
queryDocCosineSimSorted.add(outputString);
}
//Print out all the documents in order of cosine similarity
for (int i = 0; i < documentsToID.size(); i++)
{
System.out.println(queryDocCosineSimSorted.poll());
}
}
private int chooseK(SingularValueDecomposition svd)
{
//start with k = 1
int bestK = 1;
double minFrobNorm = 0.0;
System.out.println();
System.out.println("Choosing Best K based on Min. Frobenius Norm...");
System.out.println();
for (int i = 1; i < numberDocs; i++)
{
Matrix Ureduced = svd.getU().copy().getMatrix(0,svd.getU().getRowDimension()-1,0,i-1);
Matrix Sreduced = svd.getS().copy().getMatrix(0,i-1,0,i-1);
Matrix VtransposeReduced = svd.getV().copy().getMatrix(0,i-1,0,svd.getV().getColumnDimension()-1);
Matrix Xreduced = Ureduced.times(Sreduced.times(VtransposeReduced));
double currentFrobNorm = Xreduced.minus(A).normF();
//System.out.println("k = "+i+", FrobNorm = "+currentFrobNorm);
if (i != 1)
{
if (currentFrobNorm < minFrobNorm)
{
minFrobNorm = currentFrobNorm;
bestK = i;
}
} else {
minFrobNorm = currentFrobNorm;
}
}
System.out.println("Best K found: "+bestK);
System.out.println();
return bestK;
}
public void run(int givenK)
{
invertedIndexToDocTermMatrix();
A = new Matrix(termDocsMatrix);
SingularValueDecomposition svd = new SingularValueDecomposition(A);
//printMatrix(A.getArray());
if (givenK == 0)
{
k = chooseK(svd);
} else {
k = givenK;
}
//System.out.println();
//printMatrix(svd.getU().getArray());
U = svd.getU().copy();
//printMatrix(svd.getS().getArray());
S = svd.getS().copy();
//printMatrix(svd.getV().getArray());
Vt = svd.getV().copy();
reduceSVDMatrices(k,svd);
//System.out.println();
//printMatrix(Sk.getArray());
//System.out.println();
//printMatrix(Vtk.getArray());
SkInverseUkTranspose = Sk.inverse().times(Uk.transpose()).copy();
createQueryVector();
queryK = SkInverseUkTranspose.times(queryVectorMatrix);
querySimilarityToDocs();
}
public static void main(String[] args){
if (args.length > 0 && (args[0].equals("index") || args[0].equals("search")))
{
if (args[0].equals("index"))
{
if ((args.length >= 2) || (args.length <= 4))
{
String collection_dir = args[1];
String index_dir = args[2];
String stopwords_file = null;
if (args.length == 4)
{
stopwords_file = args[3];
}
Indexer index = new Indexer();
index.makeIndex(collection_dir, index_dir, stopwords_file);
} else {
System.out.println("Invalid number of arguments, need to provide collection_dir, index_dir and optionally a stopwords text file.");
}
} else {
if (args.length >= 4)
{
//valid search
String index_dir = args[1];
int k = 0;
if (args[2].equals("auto"))
{
k = 0;
} else {
k = Integer.parseInt(args[2].trim());
}
String[] query_terms = new String[args.length - 3];
for (int i = 3; i < args.length; i++)
{
query_terms[i-3] = args[i].trim();
}
soda soda = new soda(query_terms, index_dir);
soda.run(k);
} else {
System.out.println("Invalid number of arguments, need to provide index_dir, k value and at least 1 keyword");
}
}
} else {
System.out.println("to index use: soda index collection_dir index_dir [stopwords.txt]\n");
System.out.println("to search use: soda search index_dir k[=number or 'auto'] keyword1 [keyword2 keyword3 ...]\n");
}
}
}