-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPearsonMetric.java
executable file
·53 lines (45 loc) · 1.23 KB
/
PearsonMetric.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
/**
* Compute the Pearson similarity between profiles
*
* Michael O'Mahony
* 20/01/2011
*/
package similarity.metric;
import java.util.Set;
import profile.Profile;
public class PearsonMetric implements SimilarityMetric
{
/**
* constructor - creates a new PearsonMetric object
*/
public PearsonMetric()
{
}
/**
* computes the similarity between profiles
* @param profile 1
* @param profile 2
*/
public double getSimilarity(final Profile p1, final Profile p2)
{
double sum_r1 = 0;
double sum_r1_sq = 0;
double sum_r2 = 0;
double sum_r2_sq = 0;
double sum_r1_r2 = 0;
Set<Integer> common = p1.getCommonIds(p2);
for(Integer id: common)
{
double r1 = p1.getValue(id).doubleValue();
double r2 = p2.getValue(id).doubleValue();
sum_r1 += r1;
sum_r1_sq += r1 * r1;
sum_r2 += r2;
sum_r2_sq += r2 * r2;
sum_r1_r2 += r1 * r2;
}
double above = (common.size() > 0) ? sum_r1_r2 - (sum_r1 * sum_r2) / common.size() : 0;
double below = (common.size() > 0) ? Math.sqrt( (sum_r1_sq - (sum_r1 * sum_r1) / common.size()) * (sum_r2_sq - (sum_r2 * sum_r2) / common.size()) ) : 0;
return (below > 0) ? above / below : 0;
}
}