Integer uindex = userIndexMap.get(userID);
item.setEntry(uindex, rating);
// update user History
RealVector user = userHistory.get(userID);
if (user == null) {
user = new OpenMapRealVector(numOfItems);
userHistory.put(userID, user);
}
user.setEntry(iindex, rating);
}
itemVectors.put(itemID, item);
}
// calculate sim
Map<Integer, RealVector> itemSimilarity = new HashMap<Integer, RealVector>();
List<Integer> item1List = new ArrayList<Integer>(itemIndexMap.keySet());
List<Integer> item2List = new ArrayList<Integer>(item1List);
int numSimilarItems = 100;
Comparator<IndexAndScore> comparator = new IndexAndScoreComparator();
Map<Integer, Queue<IndexAndScore>> topItemSimilarity =
new HashMap<Integer, Queue<IndexAndScore>>();
for (Integer itemID1 : item1List) {
item2List.remove(0);
Integer index1 = itemIndexMap.get(itemID1);
for (Integer itemID2: item2List) {
RealVector vector1 = itemVectors.get(itemID1);
RealVector vector2 = itemVectors.get(itemID2);
double score = vector1.cosine(vector2);
if (score > params.threshold) {
Integer index2 = itemIndexMap.get(itemID2);
setTopItemSimilarity(topItemSimilarity, itemID1, index2, score, numSimilarItems,
comparator);
setTopItemSimilarity(topItemSimilarity, itemID2, index1, score, numSimilarItems,
comparator);
}
}
}
for (Map.Entry<Integer, Queue<IndexAndScore>> entry : topItemSimilarity.entrySet()) {
Iterator<IndexAndScore> it = entry.getValue().iterator();
RealVector vector = new OpenMapRealVector(numOfItems);
while (it.hasNext()) {
IndexAndScore d = it.next();
vector.setEntry(d.index, d.score);
}
itemSimilarity.put(entry.getKey(), vector);
}
return new CollaborativeFilteringModel(itemSimilarity, userHistory);