Example usage for org.apache.mahout.cf.taste.impl.model GenericPreference GenericPreference

List of usage examples for org.apache.mahout.cf.taste.impl.model GenericPreference GenericPreference

Introduction

In this page you can find the example usage for org.apache.mahout.cf.taste.impl.model GenericPreference GenericPreference.

Prototype

public GenericPreference(long userID, long itemID, float value) 

Source Link

Usage

From source file:alto.plugin.webradio.recommender.MongoDBDataModel.java

License:Apache License

private void buildModel() throws UnknownHostException {
    userIsObject = false;/* www. j a va  2 s.co m*/
    itemIsObject = false;
    idCounter = 0;
    preferenceIsString = true;
    Mongo mongoDDBB = new Mongo(mongoHost, mongoPort);
    DB db = mongoDDBB.getDB(mongoDB);
    mongoTimestamp = new Date(0);
    FastByIDMap<Collection<Preference>> userIDPrefMap = new FastByIDMap<Collection<Preference>>();
    if (!mongoAuth || db.authenticate(mongoUsername, mongoPassword.toCharArray())) {
        collection = db.getCollection(mongoCollection);
        collectionMap = db.getCollection(mongoMapCollection);
        DBObject indexObj = new BasicDBObject();
        indexObj.put("element_id", 1);
        collectionMap.ensureIndex(indexObj);
        indexObj = new BasicDBObject();
        indexObj.put("long_value", 1);
        collectionMap.ensureIndex(indexObj);
        collectionMap.remove(new BasicDBObject());
        DBCursor cursor = collection.find();
        while (cursor.hasNext()) {
            Map<String, Object> user = (Map<String, Object>) cursor.next().toMap();
            if (!user.containsKey("deleted_at")) {
                long userID = Long.parseLong(fromIdToLong(getID(user.get(mongoUserID), true), true));
                long itemID = Long.parseLong(fromIdToLong(getID(user.get(mongoItemID), false), false));
                float ratingValue = getPreference(user.get(mongoPreference));
                Collection<Preference> userPrefs = userIDPrefMap.get(userID);
                if (userPrefs == null) {
                    userPrefs = Lists.newArrayListWithCapacity(2);
                    userIDPrefMap.put(userID, userPrefs);
                }
                userPrefs.add(new GenericPreference(userID, itemID, ratingValue));
                if (user.containsKey("created_at")
                        && mongoTimestamp.compareTo(getDate(user.get("created_at"))) < 0) {
                    mongoTimestamp = getDate(user.get("created_at"));
                }
            }
        }
    }
    delegate = new GenericDataModel(GenericDataModel.toDataMap(userIDPrefMap, true));
}

From source file:com.msiiplab.recsys.rwr.GLRecommenderIRStatsEvaluator.java

License:Apache License

protected PreferenceArray getPreferenceArray(List<RecommendedItem> recommendedItems, long userID) {
    ArrayList<Preference> userPredictionArray = new ArrayList<Preference>();
    for (int i = 0; i < recommendedItems.size(); i++) {
        RecommendedItem item = recommendedItems.get(i);
        userPredictionArray.add(new GenericPreference(userID, item.getItemID(), item.getValue()));
    }//from   w ww . j  av  a2s  .c o m
    PreferenceArray userPredictions = new GenericUserPreferenceArray(userPredictionArray);
    userPredictions.sortByValueReversed();
    return userPredictions;
}

From source file:com.paradigma.recommender.db.MongoDBDataModel.java

License:Apache License

private void buildModel() throws UnknownHostException, MongoException {
    userIsObject = false;/* ww w.  j ava2 s  . c  o  m*/
    itemIsObject = false;
    idCounter = 0;
    preferenceIsString = true;
    Mongo mongoDDBB = new Mongo(mongoHost, mongoPort);
    DB db = mongoDDBB.getDB(mongoDB);
    mongoTimestamp = new Date(0);
    FastByIDMap<Collection<Preference>> userIDPrefMap = new FastByIDMap<Collection<Preference>>();
    if (!mongoAuth || (mongoAuth && db.authenticate(mongoUsername, mongoPassword.toCharArray()))) {
        collection = db.getCollection(mongoCollection);
        collectionMap = db.getCollection(MONGO_MAP_COLLECTION);
        DBObject indexObj = new BasicDBObject();
        indexObj.put("element_id", 1);
        collectionMap.ensureIndex(indexObj);
        indexObj = new BasicDBObject();
        indexObj.put("long_value", 1);
        collectionMap.ensureIndex(indexObj);
        collectionMap.remove(new BasicDBObject());
        DBCursor cursor = collection.find();
        while (cursor.hasNext()) {
            Map<String, Object> user = (Map<String, Object>) cursor.next().toMap();
            if (!user.containsKey("deleted_at")) {
                long userID = Long.parseLong(fromIdToLong(getID(user.get(mongoUserID), true), true));
                long itemID = Long.parseLong(fromIdToLong(getID(user.get(mongoItemID), false), false));
                float ratingValue = getPreference(user.get(mongoPreference));
                Collection<Preference> userPrefs = userIDPrefMap.get(userID);
                if (userPrefs == null) {
                    userPrefs = Lists.newArrayListWithCapacity(2);
                    userIDPrefMap.put(userID, userPrefs);
                }
                userPrefs.add(new GenericPreference(userID, itemID, ratingValue));
                if (user.containsKey("created_at")
                        && mongoTimestamp.compareTo(getDate(user.get("created_at"))) < 0) {
                    mongoTimestamp = getDate(user.get("created_at"));
                }
            }
        }
    }
    delegate = new GenericDataModel(GenericDataModel.toDataMap(userIDPrefMap, true));
}

From source file:de.apaxo.bedcon.AnimalFoodRecommender.java

License:Open Source License

public void initDataModel() {
    FastByIDMap<PreferenceArray> preferenceMap = new FastByIDMap<PreferenceArray>();
    for (int i = 0; i < animals.size(); i++) {
        List<Preference> userPreferences = new ArrayList<Preference>();
        long userId = id2thing.toLongID(animals.get(i));
        for (int j = 0; j < foods.size(); j++) {
            if (preferences[i][j] != null) {
                userPreferences/*from   w  ww  .ja va2  s  . c  o m*/
                        .add(new GenericPreference(userId, id2thing.toLongID(foods.get(j)), preferences[i][j]));
            }
        }
        GenericUserPreferenceArray userArray = new GenericUserPreferenceArray(userPreferences);
        preferenceMap.put(userId, userArray);
    }
    model = new GenericDataModel(preferenceMap);
}

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  ww  w  .j a v a2 s  . 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);
    }
}

From source file:edu.carleton.comp4601.cf.dao.SimpleDataRecommender.java

License:Open Source License

public void initDataModel() {
    FastByIDMap<PreferenceArray> preferenceMap = new FastByIDMap<PreferenceArray>();
    for (int i = 0; i < users.length; i++) {
        List<Preference> userPreferences = new ArrayList<Preference>();
        long userId = id2thing.toLongID(users[i]);
        for (int j = 0; j < items.length; j++) {
            if (ratings[i][j] != -1) {
                //               System.out.println(userId+" | "+items[j] + " | "+ ratings[i][j]);
                userPreferences.add(new GenericPreference(userId, id2thing.toLongID(items[j]), ratings[i][j]));
            }/*w  ww.ja  v  a 2  s  . c  o  m*/
        }
        GenericUserPreferenceArray userArray = new GenericUserPreferenceArray(userPreferences);
        preferenceMap.put(userId, userArray);
    }
    model = new GenericDataModel(preferenceMap);
}

From source file:edu.uniandes.yelp.recommender.MongoDBDataModel.java

private void buildModel() throws UnknownHostException {
    userIsObject = false;//w  ww  . jav a 2  s  .  c o  m
    itemIsObject = false;
    idCounter = 0;
    preferenceIsString = true;
    MongoClient mongoDDBB = new MongoClient(mongoHost, mongoPort);
    DB db = mongoDDBB.getDB(mongoDB);
    mongoTimestamp = new Date(0);
    FastByIDMap<Collection<Preference>> userIDPrefMap = new FastByIDMap<>();
    if (!mongoAuth) {
        collection = db.getCollection(mongoCollection);
        collectionMap = db.getCollection(mongoMapCollection);
        DBObject indexObj = new BasicDBObject();
        indexObj.put("element_id", 1);
        collectionMap.createIndex(indexObj);
        indexObj = new BasicDBObject();
        indexObj.put("long_value", 1);
        collectionMap.createIndex(indexObj);
        collectionMap.remove(new BasicDBObject());
        DBCursor cursor = collection.find();
        while (cursor.hasNext()) {
            Map<String, Object> user = (Map<String, Object>) cursor.next().toMap();
            if (!user.containsKey("deleted_at")) {
                long userID = Long.parseLong(fromIdToLong(getID(user.get(mongoUserID), true), true));
                long itemID = Long.parseLong(fromIdToLong(getID(user.get(mongoItemID), false), false));
                float ratingValue = getPreference(user.get(mongoPreference));
                Collection<Preference> userPrefs = userIDPrefMap.get(userID);
                if (userPrefs == null) {
                    userPrefs = new ArrayList<>(2);
                    userIDPrefMap.put(userID, userPrefs);
                }
                userPrefs.add(new GenericPreference(userID, itemID, ratingValue));
                if (user.containsKey("created_at")
                        && mongoTimestamp.compareTo(getDate(user.get("created_at"))) < 0) {
                    mongoTimestamp = getDate(user.get("created_at"));
                }
            }
        }
    }
    delegate = new GenericDataModel(GenericDataModel.toDataMap(userIDPrefMap, true));
}

From source file:javasensei.db.managments.RankingManager.java

public FastByIDMap buildDataModel(DBCollection rankings, String fieldNameUserId, String fieldNameItemId,
        String fieldNameValue) {/*from  ww w. j ava2  s .c  o m*/
    //Obtenemos todos los ranking actuales y los almacenamos en el archivo csv
    DBCursor cursor = rankings.find();
    FastByIDMap<PreferenceArray> userData = new FastByIDMap<>();

    if (cursor.count() > 0) {

        List<Preference> preferences = new ArrayList<>();
        Long idLastUser = null;

        while (cursor.hasNext()) {
            DBObject object = cursor.next();
            Long idItem = new Double(object.get(fieldNameItemId).toString()).longValue();
            Long idCurrentUser = new Double(object.get(fieldNameUserId).toString()).longValue();
            Float value = new Float(object.get(fieldNameValue).toString());

            if (idLastUser == null || !idCurrentUser.equals(idLastUser)) {
                if (preferences.size() > 0) {
                    userData.put(idLastUser, new GenericUserPreferenceArray(preferences));
                    preferences.clear();
                }
                idLastUser = idCurrentUser;
            }

            preferences.add(new GenericPreference(idLastUser, idItem, value));

            if (!cursor.hasNext()) {
                userData.put(idLastUser, new GenericUserPreferenceArray(preferences));
            }
        }

        System.out.println(userData);
    }

    return userData;
}

From source file:lib.eval.AbstractRecommenderEvaluator.java

License:Apache License

private void processOneUser(double trainingPercentage, FastByIDMap<PreferenceArray> trainingUsers,
        FastByIDMap<PreferenceArray> testUserPrefs, long userID, DataModel dataModel) throws TasteException {
    List<Preference> trainingPrefs = null;
    List<Preference> testPrefs = null;
    PreferenceArray prefs = dataModel.getPreferencesFromUser(userID);
    int size = prefs.length();
    for (int i = 0; i < size; i++) {
        Preference newPref = new GenericPreference(userID, prefs.getItemID(i), prefs.getValue(i));
        if (random.nextDouble() < trainingPercentage) {
            if (trainingPrefs == null) {
                trainingPrefs = new ArrayList<Preference>(3);
            }/*from  w ww.  j a  v  a  2 s.  c  o m*/
            trainingPrefs.add(newPref);
        } else {
            if (testPrefs == null) {
                testPrefs = new ArrayList<Preference>(3);
            }
            testPrefs.add(newPref);
        }
    }
    if (trainingPrefs != null) {
        trainingUsers.put(userID, new GenericUserPreferenceArray(trainingPrefs));
        if (testPrefs != null) {
            testUserPrefs.put(userID, new GenericUserPreferenceArray(testPrefs));
        }
    }
}

From source file:net.recommenders.rival.recommend.frameworks.mahout.DataModelWrapper.java

License:Apache License

/**
 * Constructs the wrapper using the provided model.
 *
 * @param model the model to be used to create the wrapped model
 *///from  www . ja va2s  .  c om
public DataModelWrapper(final net.recommenders.rival.core.TemporalDataModelIF<Long, Long> model) {
    FastByIDMap<Collection<Preference>> data = new FastByIDMap<Collection<Preference>>();
    FastByIDMap<FastByIDMap<Long>> timestampData = new FastByIDMap<FastByIDMap<Long>>();
    for (Long u : model.getUserItemPreferences().keySet()) {
        List<Preference> prefs = new ArrayList<Preference>();
        FastByIDMap<Long> userTimestamps = new FastByIDMap<Long>();
        timestampData.put(u, userTimestamps);
        for (Long i : model.getUserItemPreferences().get(u).keySet()) {
            Set<Long> timestamps = model.getUserItemTimestamps().get(u).get(i);
            long t = -1;
            if (timestamps != null) {
                for (Long tt : timestamps) {
                    t = tt;
                    break;
                }
            }
            userTimestamps.put(i, t);
            prefs.add(new GenericPreference(u, i, model.getUserItemPreferences().get(u).get(i).floatValue()));
        }
        data.put(u, prefs);
    }

    FastByIDMap<PreferenceArray> userData = GenericDataModel.toDataMap(data, true);
    wrapper = new GenericDataModel(userData, timestampData);
}