Reputation: 15
I'm trying to code adjusted cosine similarity in PHP.
I built my data like this :
$data[UserID][ItemID] = Rating
data example :
$data[1][1] = 5;
$data[1][2] = 3;
$data[1][3] = 4;
$data[2][1] = 3;
$data[2][2] = 2;
$data[2][4] = 3;
$data[2][5] = 3;
$data[3][1] = 4;
$data[3][3] = 3;
$data[3][5] = 5;
$data[4][1] = 1;
$data[4][2] = 4;
$data[4][4] = 2;
$data[4][5] = 1;
$data[5][3] = 4;
$data[5][4] = 3;
I want to write a function to calculate the adjusted cosine of 2 items, like
adjusted_cosine(itemID1,itemID2)
Upvotes: 0
Views: 2931
Reputation: 13088
I think this ought to do it:
sim(i,j) {
item1 = 0
item2 = 0
// calculate the sums for the ith and jth items
// minus each users' avg rating.
for (k = 0; k < length(data); k++) {
item1 += (data[k][i] - avg(data[k]))
item2 += (data[k][j] - avg(data[k]))
}
result (item1*item2)/(sqrt(item1*item1)*sqrt(item2*item2))
return result
}
You'll still need to implement the average function but I suppose a simple mean will do for that.
Upvotes: 2