List of usage examples for org.apache.mahout.cf.taste.impl.similarity LogLikelihoodSimilarity LogLikelihoodSimilarity
public LogLikelihoodSimilarity(DataModel dataModel)
From source file:ItemRecommender.java
License:Apache License
/** * Creates a list of recommendations using item based collaborative filtering * /* w ww . j a v a 2 s . c o m*/ * @param model a model containing information about users preferences for items. Fetched from "collaborative_view" in the database * @return the list of recommendations made */ public ArrayList<CollaborativeRecommendation> RunItemRecommender(DataModel model) { ArrayList<CollaborativeRecommendation> recommendedItemsList = new ArrayList<CollaborativeRecommendation>(); try { /* Returns the degree of similarity, of two items, based on the preferences that users have expressed for the items. */ ItemSimilarity sim = new LogLikelihoodSimilarity(model); /* Given a datamodel and a similarity to produce the recommendations */ GenericItemBasedRecommender recommender = new GenericItemBasedRecommender(model, sim); this.recommender = recommender; List<RecommendedItem> recommendations = recommender.recommend(this.userId, 167); /* Looping through all recommendations and putting up to 167 items in the collaborative recommender list*/ if (!recommendations.isEmpty()) { for (RecommendedItem recommendation : recommendations) { recommendedItemsList .add(new CollaborativeRecommendation(recommendation, (int) this.userId, "item")); } } else { /*There are no recommendations for this user*/ System.out.println("No recommendations for this user in itembased"); } } catch (TasteException e) { e.printStackTrace(); } return recommendedItemsList; }
From source file:cf.wikipedia.WikipediaTasteItemItemDemo.java
License:Apache License
public static void main(String[] args) throws IOException, TasteException, SAXException, ParserConfigurationException { String recsFile = args[0];/*from w w w .j a v a 2 s . c o m*/ String docIdsTitle = args[1]; long userId = Long.parseLong(args[2]); //Integer neighbors = Integer.parseInt(args[2]); InputSource is = new InputSource(new FileInputStream(docIdsTitle)); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false); SAXParser sp = factory.newSAXParser(); WikiContentHandler handler = new WikiContentHandler(); sp.parse(is, handler); //create the data model FileDataModel dataModel = new FileDataModel(new File(recsFile)); //Create an ItemSimilarity ItemSimilarity itemSimilarity = new LogLikelihoodSimilarity(dataModel); //Create an Item Based Recommender ItemBasedRecommender recommender = new GenericItemBasedRecommender(dataModel, itemSimilarity); //Get the recommendations List<RecommendedItem> recommendations = recommender.recommend(userId, 5); TasteUtils.printRecs(recommendations, handler.map); }
From source file:cf.wikipedia.WikipediaTasteItemRecDemo.java
License:Apache License
public static void main(String[] args) throws IOException, TasteException, SAXException, ParserConfigurationException { String recsFile = args[0];/*from w ww . jav a2s . c om*/ String docIdsTitle = args[1]; long itemId = Long.parseLong(args[2]); Integer numRecs = Integer.parseInt(args[3]); //Integer neighbors = Integer.parseInt(args[2]); InputSource is = new InputSource(new FileInputStream(docIdsTitle)); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false); SAXParser sp = factory.newSAXParser(); WikiContentHandler handler = new WikiContentHandler(); //load the ids and titles sp.parse(is, handler); //create the data model FileDataModel dataModel = new FileDataModel(new File(recsFile)); //Create an ItemSimilarity ItemSimilarity itemSimilarity = new LogLikelihoodSimilarity(dataModel); //Create an Item Based Recommender ItemBasedRecommender recommender = new GenericItemBasedRecommender(dataModel, itemSimilarity); //Get the recommendations for the Item List<RecommendedItem> simItems = recommender.mostSimilarItems(itemId, numRecs); TasteUtils.printRecs(simItems, handler.map); }
From source file:cf.wikipedia.WikipediaTasteItemSimilarity.java
License:Apache License
public static void main(String[] args) throws IOException, TasteException, SAXException, ParserConfigurationException { String recsFile = args[0];//from w w w . jav a2 s . co m String docIdsTitle = args[1]; long itemId1 = Long.parseLong(args[2]); long itemId2 = Long.parseLong(args[3]); //Integer neighbors = Integer.parseInt(args[2]); InputSource is = new InputSource(new FileInputStream(docIdsTitle)); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false); SAXParser sp = factory.newSAXParser(); WikiContentHandler handler = new WikiContentHandler(); //load the ids and titles sp.parse(is, handler); //create the data model FileDataModel dataModel = new FileDataModel(new File(recsFile)); //Create an ItemSimilarity ItemSimilarity itemSimilarity = new LogLikelihoodSimilarity(dataModel); double res = itemSimilarity.itemSimilarity(itemId1, itemId2); System.out.println("Result: " + res); }
From source file:com.buddycloud.channeldirectory.search.handler.common.mahout.ChannelRecommender.java
License:Apache License
public ChannelRecommender(Properties properties) throws TasteException { this.recommenderDataModel = createDataModel(properties); DataModel dataModel = recommenderDataModel.getDataModel(); UserSimilarity userSimilarity = new CachingUserSimilarity(new LogLikelihoodSimilarity(dataModel), MAX_CACHE_SIZE);//from w w w. j a va 2s . co m this.userNeighborhood = new NearestNUserNeighborhood(10, Double.NEGATIVE_INFINITY, userSimilarity, dataModel, 1.0); this.userRecommender = new GenericBooleanPrefUserBasedRecommender(dataModel, userNeighborhood, userSimilarity); this.itemSimilarity = new LogLikelihoodSimilarity(dataModel); }
From source file:com.corchado.testRecomender.recomendador.java
/** * @param args the command line arguments * @throws java.io.IOException/*w w w.j av a 2s . c om*/ * @throws org.apache.mahout.cf.taste.common.TasteException */ public static void main(String[] args) throws IOException, TasteException { final Scanner entrada = new Scanner(System.in); DataModel model = new FileDataModel(new File("ml-100k/ua.base")); UserSimilarity similarity = null; int obciones; System.out.println("RECOMENDADOR MEDIANTE FILTRADO COLABORATIVO"); do { System.out.println("Seleccione la funcion de similitud a utilizar para recomendar"); System.out.println("marque 1 para la funcion euclidiana"); System.out.println("marque 2 para la funcion de Pearson"); System.out.println("marque 3 para la funcion de Log-likelihood"); System.out.println("marque 4 para la funcion de Tanimoto"); obciones = entrada.nextInt(); switch (obciones) { case 1: similarity = new EuclideanDistanceSimilarity(model); break; case 2: similarity = new PearsonCorrelationSimilarity(model); break; case 3: similarity = new LogLikelihoodSimilarity(model); break; case 4: similarity = new TanimotoCoefficientSimilarity(model); break; } } while (obciones != 1 && obciones != 2 && obciones != 3 && obciones != 4); int queHago = 0; try { do { System.out.println("\n Seleccione... "); System.out.println("1 para realizar una recomendacion "); System.out.println("2 si quiere probar una recomendacion "); System.out.println("3 para evaluar precision y recall"); System.out.println("4 si quiere salir"); queHago = entrada.nextInt(); switch (queHago) { case 1: System.out.println("Recomendando..."); Recomendar(entrada, model, similarity); break; case 2: System.out.println( "Realizando una prueba al recomendador tomado como conjunto de entrenamiento el 70% " + "del dataset y el 30% como conjunto de prueba. Ademas se evalua mediante el promedio de las diferencias." + "Mientras mas pequeo es este valor mejor es la recomendacion"); System.out.println("Si el dataset es muy grande la evaluacion puede tardar un poquito.."); Probar(entrada, model, similarity); break; case 3: System.out.println( "Evaluando precision y recall tomando como limite entre una recomendacion bueno o mala " + "la suma entre la media y la desviaci'on estandar (threshold = + ?)..."); evaluarPrecicionRecall(entrada, model, similarity); break; } } while (queHago != 4); } catch (IOException | TasteException e) { System.out.println(e.getMessage()); } }
From source file:com.corchado.testRecomender.recomendadorUI.java
private String funcionSimilitud() throws TasteException { String funcionSimilitud = SpinnerFuncionsmilitud.getValue().toString(); switch (funcionSimilitud) { case "Distancia Euclideana": similarity = new EuclideanDistanceSimilarity(model); break;//from w w w. ja va 2 s . c o m case "Correlacin de Pearson": similarity = new PearsonCorrelationSimilarity(model); break; case "log-likelihood": similarity = new LogLikelihoodSimilarity(model); break; case "Coheficiente de Tanimoto": similarity = new TanimotoCoefficientSimilarity(model); break; } return funcionSimilitud; }
From source file:com.spreecommerce.recommender.ProductRecommender.java
License:Apache License
/** * <p>Alternate constructor that takes a {@link DataModel} argument, which allows this {@link Recommender} * to be used with the {@link org.apache.mahout.cf.taste.eval.RecommenderEvaluator} framework.</p> * * @param dataModel data model/* w ww . ja v a2s. c o m*/ * @throws TasteException if an error occurs while initializing this {@link GroupLensRecommender} */ public ProductRecommender(DataModel dataModel) throws TasteException, IOException { ItemSimilarity itemSimilarity = new LogLikelihoodSimilarity(dataModel); recommender = new GenericItemBasedRecommender(dataModel, itemSimilarity); }
From source file:com.thegoodlife2015.servlet.recServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w w w .j a v a 2s . c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs * @throws org.apache.mahout.cf.taste.common.TasteException */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, TasteException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //specifying the number of recommendations to be generated int noOfRecommendations = 20; String fbID = request.getParameter("fbID"); long fbIDL = Long.parseLong(fbID); // Specifications tables String tablename = "rating"; String col1 = "fbID"; String col2 = "offerID"; String col3 = "rate"; //Input for database connections // grab environment variable String host = System.getenv("OPENSHIFT_MYSQL_DB_HOST"); String servername; String username; String password; String dbname; String port; String PROPS_FILENAME = "/connection.properties"; if (host != null) { // this is production environment // obtain database connection properties from environment variables servername = host; port = System.getenv("OPENSHIFT_MYSQL_DB_PORT"); dbname = System.getenv("OPENSHIFT_APP_NAME"); username = System.getenv("OPENSHIFT_MYSQL_DB_USERNAME"); password = System.getenv("OPENSHIFT_MYSQL_DB_PASSWORD"); //out.println(servername + " " + port + " " + dbname + " " + username + " " + password); } else { try { // Retrieve properties from connection.properties via the CLASSPATH // WEB-INF/classes is on the CLASSPATH InputStream is = ConnectionManager.class.getResourceAsStream(PROPS_FILENAME); Properties props = new Properties(); props.load(is); // load database connection details servername = props.getProperty("db.host"); port = props.getProperty("db.port"); dbname = props.getProperty("db.name"); username = props.getProperty("db.user"); password = props.getProperty("db.password"); //out.println(servername + " " + port + " " + dbname + " " + username + " " + password); } catch (Exception ex) { // unable to load properties file String message = "Unable to load '" + PROPS_FILENAME + "'."; out.println(message); Logger.getLogger(ConnectionManager.class.getName()).log(Level.SEVERE, message, ex); throw new RuntimeException(message, ex); } } //setup for second connection java.sql.Connection conn = null; java.sql.Statement stmt = null; ResultSet rs = null; boolean hasRec = false; try { ///Initialize connection for Mahout input MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setServerName(servername); dataSource.setUser(username); dataSource.setPassword(password); dataSource.setDatabaseName(dbname); MySQLJDBCDataModel dataModel = new MySQLJDBCDataModel(dataSource, tablename, col1, col2, col3, null); /*Specifies the Similarity algorithm*/ ItemSimilarity itemSimilarity = new LogLikelihoodSimilarity(dataModel); /*Initalizing the recommender */ ItemBasedRecommender recommender = new GenericItemBasedRecommender(dataModel, itemSimilarity); List<RecommendedItem> recommendations = null; try { recommendations = recommender.recommend(fbIDL, noOfRecommendations); } catch (Exception e) { RandomRecommender rRecommender = new RandomRecommender(dataModel); recommendations = rRecommender.recommend(fbIDL, noOfRecommendations); } finally { // if (recommendations.size() < noOfRecommendations) { // int randomInt = noOfRecommendations - recommendations.size(); // RandomRecommender rRecommender = new RandomRecommender(dataModel); // recommendations.addAll(rRecommender.recommend(fbIDL, randomInt)); // } while (recommendations.size() < noOfRecommendations) { int randomInt = noOfRecommendations - recommendations.size(); RandomRecommender rRecommender = new RandomRecommender(dataModel); recommendations.addAll(rRecommender.recommend(fbIDL, randomInt)); recommendations = new ArrayList<>(new HashSet<>(recommendations)); } } if (recommendations.size() >= 0) { JSONObject jsonObject = getJsonFromMyFormObject(recommendations, fbIDL); hasRec = true; out.println(jsonObject); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (rs != null) { rs.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (stmt != null) { stmt.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } // if(!hasRec) { // out.println("{\"error\":\"user has no records\"}"); // } }
From source file:de.apaxo.bedcon.FacebookRecommender.java
License:Open Source License
/** * This function will init the recommender * it will load the CSV file from the resource folder, * parse it and create the necessary data structures * to create a recommender./*from w w w . j a va 2s .com*/ * The */ @PostConstruct public void initRecommender() { try { // get the file which is part of the WAR as URL url = getClass().getClassLoader().getResource(DATA_FILE_NAME); // create a file out of the resource File data = new File(url.toURI()); // create a map for saving the preferences (likes) for // a certain person Map<Long, List<Preference>> preferecesOfUsers = new HashMap<Long, List<Preference>>(); // use a CSV parser for reading the file // use UTF-8 as character set CSVParser parser = new CSVParser(new InputStreamReader(new FileInputStream(data), "UTF-8")); // parse out the header // we are not using the header String[] header = parser.getLine(); // should output person name log.fine(header[0] + " " + header[1]); String[] line; // go through every line while ((line = parser.getLine()) != null) { String person = line[0]; String likeName = line[1]; // other lines contained but not used // String category = line[2]; // String id = line[3]; // String created_time = line[4]; // create a long from the person name long userLong = thing2long.toLongID(person); // store the mapping for the user thing2long.storeMapping(userLong, person); // create a long from the like name long itemLong = thing2long.toLongID(likeName); // store the mapping for the item thing2long.storeMapping(itemLong, likeName); List<Preference> userPrefList; // if we already have a userPrefList use it // otherwise create a new one. if ((userPrefList = preferecesOfUsers.get(userLong)) == null) { userPrefList = new ArrayList<Preference>(); preferecesOfUsers.put(userLong, userPrefList); } // add the like that we just found to this user userPrefList.add(new GenericPreference(userLong, itemLong, 1)); log.fine("Adding " + person + "(" + userLong + ") to " + likeName + "(" + itemLong + ")"); } // create the corresponding mahout data structure from the map FastByIDMap<PreferenceArray> preferecesOfUsersFastMap = new FastByIDMap<PreferenceArray>(); for (Entry<Long, List<Preference>> entry : preferecesOfUsers.entrySet()) { preferecesOfUsersFastMap.put(entry.getKey(), new GenericUserPreferenceArray(entry.getValue())); } // create a data model dataModel = new GenericDataModel(preferecesOfUsersFastMap); // Instantiate the recommender recommender = new GenericBooleanPrefItemBasedRecommender(dataModel, new LogLikelihoodSimilarity(dataModel)); } catch (URISyntaxException e) { log.log(Level.SEVERE, "Problem with the file URL", e); } catch (FileNotFoundException e) { log.log(Level.SEVERE, DATA_FILE_NAME + " was not found", e); } catch (IOException e) { log.log(Level.SEVERE, "Error during reading line of file", e); } }