Showing posts with label mahout Dataset. Show all posts
Showing posts with label mahout Dataset. Show all posts

Saturday, January 5, 2013

Mahout Recommendations with Data Sets containing Alpha Numeric Item Ids


In real world data we can’t always ensure that the input data supplied to us in order to generate recommendations should contain only integer values for User and Item Ids. If these values or any one of these are not integers the default data models that mahout provides won’t be suitable to process our data. Here let us consider the case where out Item ID is Strings we’d define our custom data model. In our data model we need to override a method in order to read item id as string and convert the same into long and return the unique long value

Data Model Class

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;

public class AlphaItemFileDataModel extends FileDataModel {
      private final ItemMemIDMigrator  memIdMigtr = newItemMemIDMigrator();
     
      public AlphaItemFileDataModel(File dataFile) throwsIOException {
            super(dataFile);       
      }

      public AlphaItemFileDataModel(File dataFile, booleantranspose) throws IOException {
            super(dataFile, transpose);
      }

      @Override
      protected long readItemIDFromString(String value) {
            long retValue =  memIdMigtr.toLongID(value);
            if(null == memIdMigtr.toStringID(retValue)){
                  try {
                        memIdMigtr.singleInit(value);
                  } catch (TasteException e) {
                        e.printStackTrace();
                  }
            }
            return retValue;
      }
   
      String getItemIDAsString(long itemId){
            return memIdMigtr.toStringID(itemId);
      }
}

Class that defines the map to store the String to Long values

import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.FastByIDMap;
import org.apache.mahout.cf.taste.impl.model.AbstractIDMigrator;

      public  class ItemMemIDMigrator extends AbstractIDMigrator {
       
        private final FastByIDMap<String> longToString;
       
        public ItemMemIDMigrator() {
          this.longToString = new FastByIDMap<String>(100);
        }
       
        @Override
        public void storeMapping(long longID, String stringID) {
          synchronized (longToString) {
            longToString.put(longID, stringID);
          }
        }
       
        @Override
        public String toStringID(long longID) {
          synchronized (longToString) {
            return longToString.get(longID);
          }
        }
        public void singleInit(String stringID) throwsTasteException {
            storeMapping(toLongID(stringID), stringID);
        }
       
      }

In your Recommender implementation you can use this Data Model class instead of the default file data model to accept an input that contains alpha numeric Item Ids. Similar you can device the code to form a data model that would accommodate alpha numeric User Ids as well.

Generating Recommendations with mahout for Boolean data sets (data sets with no preference value)


Boolean data Sets
                Input data set that doesn’t have a preference value, ie input data set would be of the format UserId1,ItemId1
UserId2,ItemId2
Here it’d based on some data where an user either likes an item or he doesn’t, there is no preference value associated with this.

                When we use Boolean data sets we need to appropriately choose the Similarity algorithms and Recommenders

Similarity Algorithms
                For Boolean data sets we can either go in for Tanimoto Coefficient Similarity or Log Likelihood Similarity

Recommender
                We need to use Generic Boolean Pref User Based Recommender or Generic Boolean Pref Item Based Recommender

                Sample codes for generating User based and Item Based recommendations are given below

Used Based Recommender for Boolean Data Sets

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.model.file.FileDataModel;
importorg.apache.mahout.cf.taste.impl.neighborhood.ThresholdUserNeighborhood;
importorg.apache.mahout.cf.taste.impl.recommender.GenericBooleanPrefUserBasedRecommender;
importorg.apache.mahout.cf.taste.impl.similarity.TanimotoCoefficientSimilarity;
import org.apache.mahout.cf.taste.neighborhood.UserNeighborhood;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.recommender.Recommender;
import org.apache.mahout.cf.taste.similarity.UserSimilarity;

public class UserRecommender {
     
      public static void main(String args[])
      {
            // specifying the user id to which the recommendations have to be generated for
            int userId=510;
           
            //specifying the number of recommendations to be generated
            int noOfRecommendations=5;
           
            //specifying theNeighborhood size
            double thresholdValue=0.7;
           
            try
            {
                  // Data model created to accept the input file
                  FileDataModel dataModel = new FileDataModel(newFile("D://input.txt"));
                 
                  /*TanimotoCoefficientSimilarity is intended for "binary" data sets
                  where a user either expresses a generic "yes" preference for an item or has no preference.*/
                  UserSimilarity userSimilarity = newTanimotoCoefficientSimilarity(dataModel);
                 
                  /*ThresholdUserNeighborhood is preferred in situations where we go in for a
                   similarity measure between neighbors and not any number*/
                  UserNeighborhood neighborhood =newThresholdUserNeighborhood(thresholdValue, userSimilarity, dataModel);
                 
                  /*GenericBooleanPrefUserBasedRecommender is appropriate for use when no notion
                  of preference value exists in the data. */
                  Recommender recommender =newGenericBooleanPrefUserBasedRecommender(dataModel, neighborhood, userSimilarity);
                 
                  //calling the recommend method to generate recommendations
                  List<RecommendedItem> recommendations =recommender.recommend(userId, noOfRecommendations);
           
                  //
                  for (RecommendedItem recommendedItem : recommendations)
                        System.out.println(recommendedItem.getItemID());
            }
            catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            } catch (TasteException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }
           
                 
      }

}

Item Based Recommender for Boolean Data Sets

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.model.file.FileDataModel;
importorg.apache.mahout.cf.taste.impl.recommender.GenericItemBasedRecommender;
importorg.apache.mahout.cf.taste.impl.similarity.LogLikelihoodSimilarity;
importorg.apache.mahout.cf.taste.recommender.ItemBasedRecommender;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.similarity.ItemSimilarity;

public class ItemRecommender {
     
      public static void main(String args[])
      {
            // specifying the user id to which the recommendations have to be generated for
            int userId=510;
           
            //specifying the number of recommendations to be generated
            int noOfRecommendations=5;
           
            try
            {
                  // Data model created to accept the input file
                  FileDataModel dataModel = new FileDataModel(newFile("D://input.txt"));
                 
                  /*Specifies the Similarity algorithm*/
                  ItemSimilarity itemSimilarity = newLogLikelihoodSimilarity(dataModel);
                 
                  /*Initalizing the recommender */
                  ItemBasedRecommender recommender =newGenericItemBasedRecommender(dataModel, itemSimilarity);
                 
                  //calling the recommend method to generate recommendations
                  List<RecommendedItem> recommendations =recommender.recommend(userId, noOfRecommendations);
           
                  //
                  for (RecommendedItem recommendedItem : recommendations)
                        System.out.println(recommendedItem.getItemID());
            }
            catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            } catch (TasteException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }
           
      }
}


Note: For more details on basic recommendations refer generating recommendations with mahout