本文整理汇总了Java中org.apache.mahout.cf.taste.recommender.RecommendedItem类的典型用法代码示例。如果您正苦于以下问题:Java RecommendedItem类的具体用法?Java RecommendedItem怎么用?Java RecommendedItem使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
RecommendedItem类属于org.apache.mahout.cf.taste.recommender包,在下文中一共展示了RecommendedItem类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: main
import org.apache.mahout.cf.taste.recommender.RecommendedItem; //导入依赖的package包/类
public static void main(String[] args) throws IOException, TasteException {
DataModel model =
new FileDataModel(new File("data/ua.base"));
UserSimilarity similarity =
new PearsonCorrelationSimilarity(model);
UserNeighborhood neighborhood =
new NearestNUserNeighborhood(2, similarity, model);
Recommender recommender = new GenericUserBasedRecommender(
model, neighborhood, similarity);
List<RecommendedItem> recommendations = recommender.recommend(2, 1);
for (RecommendedItem recommendation : recommendations) {
logger.info(recommendation.toString());
}
logger.info("over");
}
示例2: recommend
import org.apache.mahout.cf.taste.recommender.RecommendedItem; //导入依赖的package包/类
private static void recommend(String ratingsFile, int ... userIds)
throws TasteException, IOException {
DataModel model = new FileDataModel(new File(ratingsFile));
UserSimilarity similarity = new PearsonCorrelationSimilarity(model);
UserNeighborhood neighborhood =
new NearestNUserNeighborhood(
100, similarity, model);
Recommender recommender = new GenericUserBasedRecommender(
model, neighborhood, similarity);
Recommender cachingRecommender = new CachingRecommender(recommender);
for(int userId: userIds) {
System.out.println("UserID " + userId);
List<RecommendedItem> recommendations =
cachingRecommender.recommend(userId, 2);
for(RecommendedItem item: recommendations) {
System.out.println(" item " + item.getItemID() + " score " + item.getValue());
}
}
}
示例3: main
import org.apache.mahout.cf.taste.recommender.RecommendedItem; //导入依赖的package包/类
public static void main(String[] args) throws TasteException, IOException {
DataModel model = new FileDataModel(new File("data/dataset.csv"));
ItemSimilarity similarity = new LogLikelihoodSimilarity(model);
//UserNeighborhood neighborhood = new ThresholdUserNeighborhood(0.1, similarity, model);
GenericItemBasedRecommender recommender = new GenericItemBasedRecommender(model, similarity);
List<RecommendedItem> recommendations = recommender.mostSimilarItems(18, 3);
for (RecommendedItem recommendation : recommendations) {
System.out.println(recommendation);
}
}
示例4: recommend
import org.apache.mahout.cf.taste.recommender.RecommendedItem; //导入依赖的package包/类
public List<RecommendedItem> recommend(long userId, PreferenceArray preferences) throws TasteException {
if (userExistsInDataModel(userId)) {
return recommender.recommend(userId, noItems);
}
else {
PlusAnonymousConcurrentUserDataModel plusModel = (PlusAnonymousConcurrentUserDataModel) recommender.getDataModel();
// Take an available anonymous user form the poll
Long anonymousUserID = plusModel.takeAvailableUser();
// Set temporary preferences
PreferenceArray tempPrefs = preferences;
tempPrefs.setUserID(0, anonymousUserID);
// tempPrefs.setItemID(0, itemID);
plusModel.setTempPrefs(tempPrefs, anonymousUserID);
List<RecommendedItem> results = recommender.recommend(anonymousUserID, noItems);
// Release the user back to the poll
plusModel.releaseUser(anonymousUserID);
return results;
}
}
开发者ID:PacktPublishing,项目名称:Machine-Learning-End-to-Endguide-for-Java-developers,代码行数:27,代码来源:OnlineRecommendation.java
示例5: getRecommendations
import org.apache.mahout.cf.taste.recommender.RecommendedItem; //导入依赖的package包/类
/**
* Give the recommendations based on the supplied User instance.
* This will make the calls to Mahout and ask it to give recommendations
* for the given User instance that this user is likely interested in.
* Although we speak about Users here, this can be any object type.
* Note: The recommendations that are returned are the result of the
* algorithm you use, if the results do not match your expectations, please
* try using another algorithm. See the documentation for more information.
* @param x The user object to give recommendations of.
* @param howMany The number of recommendations you would like to get.
* @param aType The type of the recommendation, either USER (in case of User
* to Item recommendations) or ITEM (in case of Item to Item recommendations)
* @return A list with recommended items that are recommended by Mahout
* for this user.
*/
public List<?> getRecommendations(Object x, int howMany, RecFieldType aType) {
if(checkAvailabilityOfRecommendations(aType) == false){
org.webdsl.logging.Logger.warn("Warning, you request to get recommendations while the recommendations taste table has not yet been filled by Mahout.\nEither wait for it to finish its background task, or call the reconstructRecommendCache function (last option should be used with care, on non-production systems only.)");
return new ArrayList<Object>();
}
long startTime = System.currentTimeMillis();
try {
long id = getIDOfObject(x, aType);
List<RecommendedItem> recommendations = aType == RecFieldType.USER ? this.userRecommenderCache.recommend(id, howMany) : this.itemRecommenderCache.recommend(id, howMany);
this.lastExecutionTime = System.currentTimeMillis() - startTime;
//org.webdsl.logging.Logger.info("Obtaining the list of recommendations took: " + this.lastExecutionTime);
return getObjectsOfIDList(recommendations, RecFieldType.ITEM);
} catch(NoSuchUserException nse){
/* Recommendations cannot be given because the user is unknown */
return new ArrayList<Object>();
} catch (Exception e){
org.webdsl.logging.Logger.error("Error, catched an exception while obtaining the recommendations! " + e);
org.webdsl.logging.Logger.error("EXCEPTION",e);
return new ArrayList<Object>();
}
}
示例6: main
import org.apache.mahout.cf.taste.recommender.RecommendedItem; //导入依赖的package包/类
public static void main(String[] args) {
try {
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setServerName("localhost");
dataSource.setUser("root");
dataSource.setPassword("root");
dataSource.setDatabaseName("rec");
JDBCDataModel dm = new MySQLJDBCDataModel(dataSource,"ratings","userid","itemid","rating","");
UserSimilarity similarity = new PearsonCorrelationSimilarity(dm);
UserNeighborhood neighbor = new NearestNUserNeighborhood(2,similarity, dm);
Recommender recommender = new GenericUserBasedRecommender(dm, neighbor, similarity);
List<RecommendedItem> list = recommender.recommend(1, 3);// recommend
// one item
// to user
// 1
for (RecommendedItem ri : list) {
System.out.println(ri);
}
} catch (Exception e) {
e.printStackTrace();
}
}
示例7: displayRecommendation
import org.apache.mahout.cf.taste.recommender.RecommendedItem; //导入依赖的package包/类
public static void displayRecommendation(
List<RecommendedItem> recommendations, DataModel dataModel)
throws TasteException {
for (LongPrimitiveIterator users = dataModel.getUserIDs(); users
.hasNext();) {
long userId = users.nextLong();
// List<RecommendedItem> recommendations =
// recommender.recommend(userId, 5);
for (RecommendedItem recommendation : recommendations) {
System.out.println(userId + "," + recommendation.getItemID()
+ "," + recommendation.getValue());
}
}
}
示例8: next
import org.apache.mahout.cf.taste.recommender.RecommendedItem; //导入依赖的package包/类
@Override
public RecommendedItem next() {
FastByIDFloatMap.MapEntry entry = countsIterator.next();
long id = entry.getKey();
float value = entry.getValue();
IDRescorer theRescorer = rescorer;
if (theRescorer != null) {
if (theRescorer.isFiltered(id)) {
return null;
}
value = (float) theRescorer.rescore(id, value);
if (!LangUtils.isFinite(value)) {
return null;
}
}
delegate.set(id, value);
return delegate;
}
示例9: next
import org.apache.mahout.cf.taste.recommender.RecommendedItem; //导入依赖的package包/类
@Override
public RecommendedItem next() {
FastByIDMap.MapEntry<float[]> entry = toFeaturesIterator.next();
long itemID = entry.getKey();
if (userTagIDs.contains(itemID)) {
return null;
}
float[] candidateFeatures = entry.getValue();
double candidateFeaturesNorm = SimpleVectorMath.norm(candidateFeatures);
double estimate = SimpleVectorMath.dot(candidateFeatures, features) / (candidateFeaturesNorm * featuresNorm);
if (!LangUtils.isFinite(estimate)) {
return null;
}
delegate.set(itemID, (float) estimate);
return delegate;
}
示例10: formatOutLine
import org.apache.mahout.cf.taste.recommender.RecommendedItem; //导入依赖的package包/类
static String formatOutLine(long id, Iterable<RecommendedItem> recs) {
StringBuilder result = new StringBuilder(100);
result.append(id);
result.append("\t[");
boolean first = true;
for (RecommendedItem rec : recs) {
if (first) {
first = false;
} else {
result.append(',');
}
result.append(rec.getItemID()).append(':').append(rec.getValue());
}
result.append("]\n");
return result.toString();
}
示例11: recommendToAnonymous
import org.apache.mahout.cf.taste.recommender.RecommendedItem; //导入依赖的package包/类
@Override
public List<TranslatedRecommendedItem> recommendToAnonymous(String[] itemIDs,
float[] values,
int howMany,
String[] rescorerParams,
String contextUserID)
throws TasteException {
long[] longItemIDs = translateItems(itemIDs);
Collection<RecommendedItem> originals;
if (contextUserID == null) {
originals = delegate.recommendToAnonymous(longItemIDs, values, howMany, rescorerParams, null);
} else {
originals =
delegate.recommendToAnonymous(longItemIDs, values, howMany, rescorerParams, translateUser(contextUserID));
}
return translate(originals);
}
示例12: consumeItems
import org.apache.mahout.cf.taste.recommender.RecommendedItem; //导入依赖的package包/类
private static List<RecommendedItem> consumeItems(URLConnection connection) throws IOException {
List<RecommendedItem> result = Lists.newArrayList();
BufferedReader reader = IOUtils.bufferStream(connection.getInputStream());
try {
CharSequence line;
while ((line = reader.readLine()) != null) {
Iterator<String> tokens = COMMA.split(line).iterator();
long itemID = Long.parseLong(tokens.next());
float value = LangUtils.parseFloat(tokens.next());
result.add(new GenericRecommendedItem(itemID, value));
}
} finally {
reader.close();
}
return result;
}
示例13: testRecommendToMany
import org.apache.mahout.cf.taste.recommender.RecommendedItem; //导入依赖的package包/类
@Test
public void testRecommendToMany() throws Exception {
ClientRecommender client = getClient();
// Adding non-existent item to make sure it is ignored
List<RecommendedItem> recs =
client.recommendToMany(new long[] {1L, 3L, Integer.MAX_VALUE}, 3, false, (String[]) null);
assertNotNull(recs);
assertEquals(3, recs.size());
log.info("{}", recs);
assertEquals(286L, recs.get(0).getItemID());
assertEquals(288L, recs.get(1).getItemID());
assertEquals(302L, recs.get(2).getItemID());
}
示例14: testRecommendToAnonymous
import org.apache.mahout.cf.taste.recommender.RecommendedItem; //导入依赖的package包/类
@Test
public void testRecommendToAnonymous() throws Exception {
ClientRecommender client = getClient();
// Adding non-existent item to make sure it is ignored
List<RecommendedItem> recs = client.recommendToAnonymous(new long[] {1L, 3L, Integer.MAX_VALUE}, 3);
assertNotNull(recs);
assertEquals(3, recs.size());
log.info("{}", recs);
assertEquals(151L, recs.get(0).getItemID());
assertEquals(50L, recs.get(1).getItemID());
assertEquals(181L, recs.get(2).getItemID());
}
示例15: testMostPopular
import org.apache.mahout.cf.taste.recommender.RecommendedItem; //导入依赖的package包/类
@Test
public void testMostPopular() throws Exception {
ClientRecommender client = getClient();
List<RecommendedItem> popular = client.mostPopularItems(3);
assertNotNull(popular);
assertEquals(3, popular.size());
log.info("{}", popular);
assertEquals(50L, popular.get(0).getItemID());
assertEquals(258L, popular.get(1).getItemID());
assertEquals(100L, popular.get(2).getItemID());
assertEquals(583.0f, popular.get(0).getValue());
assertEquals(509.0f, popular.get(1).getValue());
assertEquals(508.0f, popular.get(2).getValue());
}