-
Notifications
You must be signed in to change notification settings - Fork 0
/
NearestNeighbourhood.java
executable file
·64 lines (56 loc) · 1.67 KB
/
NearestNeighbourhood.java
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
/**
* A class that implements the "nearest neighbourhood" technique (item-based CF)
*
* Michael O'Mahony
* 20/01/2011
*/
package alg.ib.neighbourhood;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;
import similarity.SimilarityMap;
import profile.Profile;
import util.ScoredThingDsc;
public class NearestNeighbourhood extends Neighbourhood
{
private final int k; // the number of neighbours in the neighbourhood
/**
* constructor - creates a new NearestNeighbourhood object
* @param k - the number of neighbours in the neighbourhood
*/
public NearestNeighbourhood(final int k)
{
super();
this.k = k;
}
/**
* stores the neighbourhoods for all items in member Neighbour.neighbourhoodMap
* @param simMap - a map containing item-item similarities
*/
public void computeNeighbourhoods(final SimilarityMap simMap)
{
for(Integer itemId: simMap.getIds()) // iterate over each item
{
SortedSet<ScoredThingDsc> ss = new TreeSet<ScoredThingDsc>(); // for the current item, store all similarities in order of descending similarity in a sorted set
Profile profile = simMap.getSimilarities(itemId); // get the item similarity profile
if(profile != null)
{
for(Integer id: profile.getIds()) // iterate over each item in the profile
{
double sim = profile.getValue(id);
if(sim > 0)
ss.add(new ScoredThingDsc(sim, id));
}
}
// get the k most similar items (neighbours)
int counter = 0;
for(Iterator<ScoredThingDsc> iter = ss.iterator(); iter.hasNext() && counter < k; )
{
ScoredThingDsc st = iter.next();
Integer id = (Integer)st.thing;
this.add(itemId, id);
counter++;
}
}
}
}