Monday, 14 September 2015

Mahout: CityBlockSimilarity: Compute item similarity

CityBlockSimilarity is implementation of City Block distance (Also known as Manhattan distance.

if x=(a,b) and y=(c,d), the Manhatten distance between x and y is |a−c|+|b−d|.

x = (5, 3)
y = (6, 2)

Manhatten distance = |5-6| + |3-2| = 1 + 1 = 2.

x1:  1.0, 3.2, 4.8, 0.1, 3.2, 0.6, 2.2, 1.1
x2:  0.1, 5.2, 1.9, 4.2, 1.9, 0.1, 0.1, 6.0

Manhatten distance(MD) between x1 and x2 is

|1−0.1|+|3.2−5.2|+|4.8−1.9|+|0.1−4.2|+|3.2−1.9|+|0.6−0.1|+|2.2−0.1|+|1.1−6.0|

0.9+2+2.9+4.1+1.3+0.5+2.1+4.9

18.7

Following example explains how to compute ItemSimilarity between items using CityBlockSimilarity.

Let’s say I had following input data.


customer.csv
1,4,3
1,7,2
1,8,2
1,10,1
2,3,2
2,4,3
2,6,3
2,7,1
2,9,1
3,0,3
3,3,2
3,4,1
3,8,3
3,9,1
4,2,5
4,3,4
4,7,3
4,9,2
5,4,5
5,6,4
5,7,1
5,8,3


1,4,3 means customer 1 like item 4 and rated it 3
import java.io.File;
import java.io.IOException;

import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.model.file.FileDataModel;
import org.apache.mahout.cf.taste.impl.similarity.CityBlockSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;

public class CityBlockSimilarityEx {
 public static String dataFile = "/Users/harikrishna_gurram/customer.csv";

 public static void main(String args[]) throws IOException, TasteException {

  DataModel model = new FileDataModel(new File(dataFile));

  CityBlockSimilarity similarity = new CityBlockSimilarity(model);

  long itemIds[] = { 2, 3, 4, 5, 6, 7, 8, 9, 10 };

  double distance[] = similarity.itemSimilarities(1, itemIds);

  for (int i = 0; i < itemIds.length; i++) {
   System.out.println("distance between item 1 and " + itemIds[i]
     + " is " + distance[i]);
  }

 }
}

Output    
distance between item 1 and 2 is 0.5
distance between item 1 and 3 is 0.25
distance between item 1 and 4 is 0.2
distance between item 1 and 5 is 1.0
distance between item 1 and 6 is 0.3333333333333333
distance between item 1 and 7 is 0.2
distance between item 1 and 8 is 0.25
distance between item 1 and 9 is 0.25
distance between item 1 and 10 is 0.5



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment