当前位置: 首页>>代码示例>>Java>>正文


Java MutableSparseVector.fast方法代码示例

本文整理汇总了Java中org.grouplens.lenskit.vectors.MutableSparseVector.fast方法的典型用法代码示例。如果您正苦于以下问题:Java MutableSparseVector.fast方法的具体用法?Java MutableSparseVector.fast怎么用?Java MutableSparseVector.fast使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.grouplens.lenskit.vectors.MutableSparseVector的用法示例。


在下文中一共展示了MutableSparseVector.fast方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: score

import org.grouplens.lenskit.vectors.MutableSparseVector; //导入方法依赖的package包/类
/**
 * Generate item scores personalized for a particular user.  For the TFIDF scorer, this will
 * prepare a user profile and compare it to item tag vectors to produce the score.
 *
 * @param user   The user to score for.
 * @param output The output vector.  The contract of this method is that the caller creates a
 *               vector whose possible keys are all items that should be scored; this method
 *               fills in the scores.
 */
@Override
public void score(long user, @Nonnull MutableSparseVector output) {
    // Get the user's profile, which is a vector with their 'like' for each tag
    SparseVector userVector = makeUserVector(user);

    // Loop over each item requested and score it.
    // The *domain* of the output vector is the items that we are to score.
    for (VectorEntry e: output.fast(VectorEntry.State.EITHER)) {
        // Score the item represented by 'e'.
        // Get the item vector for this item
        SparseVector iv = model.getItemVector(e.getKey());

        double similarity = iv.dot(userVector)/(iv.norm()*userVector.norm());
        output.set(e.getKey(), similarity);
        // DA FARE Compute the cosine of this item and the user's profile, store it in the output vector
    }
}
 
开发者ID:paolobarbaglia,项目名称:coursera_recommender_systems,代码行数:27,代码来源:TFIDFItemScorer.java

示例2: score

import org.grouplens.lenskit.vectors.MutableSparseVector; //导入方法依赖的package包/类
/**
 * Generate item scores personalized for a particular user.  For the TFIDF scorer, this will
 * prepare a user profile and compare it to item tag vectors to produce the score.
 *
 * @param user   The user to score for.
 * @param output The output vector.  The contract of this method is that the caller creates a
 *               vector whose possible keys are all items that should be scored; this method
 *               fills in the scores.
 */
@Override
public void score(long user, @Nonnull MutableSparseVector output) {
    // Get the user's profile, which is a vector with their 'like' for each tag
    SparseVector userVector = makeUserVector(user);

    // Loop over each item requested and score it.
    // The *domain* of the output vector is the items that we are to score.
    for (VectorEntry e: output.fast(VectorEntry.State.EITHER)) {
        // Score the item represented by 'e'.
        // Get the item vector for this item
    	SparseVector iv = model.getItemVector(e.getKey());
    	

        double similarity = iv.dot(userVector)/(iv.norm()*userVector.norm());
        output.set(e.getKey(), similarity);
        // DA FARE Compute the cosine of this item and the user's profile, store it in the output vector
    }
}
 
开发者ID:paolobarbaglia,项目名称:coursera_recommender_systems,代码行数:28,代码来源:TFIDFItemScorer.java

示例3: score

import org.grouplens.lenskit.vectors.MutableSparseVector; //导入方法依赖的package包/类
/**
 * Score items in a vector. The key domain of the provided vector is the
 * items to score, and the score method sets the values for each item to its
 * score (or unsets it, if no score can be provided). The previous values
 * are discarded.
 * 
 * @param user
 *            The user ID.
 * @param scores
 *            The score vector.
 */
@Override
public void score(long user, @Nonnull MutableSparseVector scores) {
	// P = b + U.S.Vt
	if (model.getUserVector(user) == null) {
		scores.clear();
	} else {
		RealMatrix U = model.getUserVector(user);
		RealMatrix S = model.getFeatureWeights();

		for (VectorEntry e : scores.fast(VectorEntry.State.EITHER)) {
			long item = e.getKey();
			RealMatrix V = model.getItemVector(item);
			scores.set(item,
					baselineScorer.score(user, item)
							+ (U.multiply(S)).multiply(V.transpose())
									.getEntry(0, 0));
		}
	}
}
 
开发者ID:paolobarbaglia,项目名称:coursera_recommender_systems,代码行数:31,代码来源:SVDItemScorer.java

示例4: globalScore

import org.grouplens.lenskit.vectors.MutableSparseVector; //导入方法依赖的package包/类
/**
 * Score items with respect to a set of reference items.
 * 
 * @param items
 *            The reference items.
 * @param scores
 *            The score vector. Its domain is the items to be scored, and the scores should be stored into this vector.
 */
@Override
public void globalScore(@Nonnull Collection<Long> items, @Nonnull MutableSparseVector scores) {
	scores.fill(0);
	// each item's score is the sum of its similarity to each item in items, if they are
	// neighbors in the model.

	for (VectorEntry e : scores.fast(VectorEntry.State.EITHER)) {
		long item = e.getKey();
		List<ScoredId> neighbors = model.getNeighbors(item);
		double sumScore = 0;
		for (ScoredId thisNghbr : neighbors) {
			if (items.contains(thisNghbr.getId()))
				sumScore += thisNghbr.getScore();
		}
		scores.set(item, sumScore);
	}
}
 
开发者ID:rohitsinha54,项目名称:Coursera-Introduction-to-Recommender-Systems-Programming-Assignment-5,代码行数:26,代码来源:SimpleGlobalItemScorer.java

示例5: score

import org.grouplens.lenskit.vectors.MutableSparseVector; //导入方法依赖的package包/类
/**
  * Score items for a user.
  * @param user The user ID.
  * @param scores The score vector.  Its key domain is the items to score, and the scores
  *               (rating predictions) should be written back to this vector.
  */
 @Override
 public void score(long user, @Nonnull MutableSparseVector scores) {
     SparseVector ratings = getUserRatingVector(user);

     for (VectorEntry e: scores.fast(VectorEntry.State.EITHER)) {
         long item = e.getKey();
         List<ScoredId> neighbors = model.getNeighbors(item);
int nghbrCount = 0;
double numerator = 0, denominator = 0;

for(ScoredId thisNghbr : neighbors){
	if(nghbrCount < neighborhoodSize){
		if (!ratings.containsKey(thisNghbr.getId())) continue;
		double thisItemRating = ratings.get(thisNghbr.getId());
		double thisItemSimilarity = thisNghbr.getScore();

		numerator += thisItemRating * thisItemSimilarity;
		denominator += thisItemSimilarity;
		nghbrCount++;
	}
}
scores.set(item, numerator/denominator);
     }
 }
 
开发者ID:rohitsinha54,项目名称:Coursera-Introduction-to-Recommender-Systems-Programming-Assignment-5,代码行数:31,代码来源:SimpleItemItemScorer.java

示例6: score

import org.grouplens.lenskit.vectors.MutableSparseVector; //导入方法依赖的package包/类
/**
 * Score items for a user.
 * @param user The user ID.
 * @param scores The score vector.  Its key domain is the items to score, and the scores
 *               (rating predictions) should be written back to this vector.
 */
@Override
public void score(long user, @Nonnull MutableSparseVector scores) {
    SparseVector ratings = getUserRatingVector(user);

    for (VectorEntry e: scores.fast(VectorEntry.State.EITHER)) {
        long item = e.getKey();
        List<ScoredId> neighbors = model.getNeighbors(item);
        // TODO Score this item and save the score into scores
    }
}
 
开发者ID:4DD8A19D69F5324F9D49D17EF78BBBCC,项目名称:Introd_uction_to_Recom_mander_S_ystem,代码行数:17,代码来源:SimpleItemItemScorer.java

示例7: score

import org.grouplens.lenskit.vectors.MutableSparseVector; //导入方法依赖的package包/类
@Override
public void score(long user, @Nonnull MutableSparseVector scores) {
    SparseVector userVector = getUserRatingVector(user);

    // TODO Score items for this user using user-user collaborative filtering



    // This is the loop structure to iterate over items to score
    for (VectorEntry e: scores.fast(VectorEntry.State.EITHER)) {
        long itemid = e.getKey();

        //Weird method to get the top30   Please Ignore
        TreeMap<Double, Long> simMap = new TreeMap<Double, Long>();
        for (long uid: itemDao.getUsersForItem(itemid)){
            if (user != uid){
                simMap.put(-getUserUserSimilarity(user,uid),uid);
            }
        }
        int counter=0;
        double simscore = 0.0;
        double simsum = 0.0;

        for(Map.Entry<Double,Long> ent:simMap.entrySet()){
            double sim = -ent.getKey();
            long userid = ent.getValue();

            simsum+=Math.abs(sim);
            simscore+= sim* (getUserRatingVector(userid).get(itemid)- getUserRatingVector(userid).mean());
            counter++;
            if(counter>=30) break;
        }

        double result = simscore / simsum +userVector.mean();
        scores.set(e,result);


    }
}
 
开发者ID:4DD8A19D69F5324F9D49D17EF78BBBCC,项目名称:Introd_uction_to_Recom_mander_S_ystem,代码行数:40,代码来源:SimpleUserUserItemScorer.java

示例8: globalScore

import org.grouplens.lenskit.vectors.MutableSparseVector; //导入方法依赖的package包/类
/**
 * Score items with respect to a set of reference items.
 * @param items The reference items.
 * @param scores The score vector. Its domain is the items to be scored, and the scores should
 *               be stored into this vector.
 */
@Override
public void globalScore(@Nonnull Collection<Long> items, @Nonnull MutableSparseVector scores) {
	scores.fill(0);
	// score items in the domain of scores
	for (VectorEntry e: scores.fast(VectorEntry.State.EITHER)) {
		// each item's score is the sum of its similarity to each item in items, if they are
		// neighbors in the model.
		long itemId = e.getKey();
		
		// getting neighbors
		List<ScoredId> neighbors = model.getNeighbors(itemId);
		Map<Long, Double> neighMap = new HashMap<Long, Double>();
		for (ScoredId scoredId : neighbors) {
			neighMap.put(scoredId.getId(), scoredId.getScore());
		}
		
		// scoring similarity
		double score = 0.0;
		for(Long basketItem: items){
			Double similarity = 0.0;
			if(neighMap.containsKey(basketItem)) similarity = neighMap.get(basketItem);
			score += similarity;
		}
		
		// asserting score
		scores.set(e, score);
	}
}
 
开发者ID:paolobarbaglia,项目名称:coursera_recommender_systems,代码行数:35,代码来源:SimpleGlobalItemScorer.java

示例9: getItemVectors

import org.grouplens.lenskit.vectors.MutableSparseVector; //导入方法依赖的package包/类
/**
 * Load the data into memory, indexed by item.
 * @return A map from item IDs to item rating vectors. Each vector contains users' ratings for
 * the item, keyed by user ID.
 */
public Map<Long,ImmutableSparseVector> getItemVectors() {
	// set up storage for building each item's rating vector
	LongSet items = itemDao.getItemIds();
	// map items to maps from users to ratings
	Map<Long,Map<Long,Double>> itemData = new HashMap<Long, Map<Long, Double>>();
	for (long item: items) {
		itemData.put(item, new HashMap<Long, Double>());
	}
	// itemData should now contain a map to accumulate the ratings of each item

	// stream over all user events
	Cursor<UserHistory<Event>> stream = userEventDao.streamEventsByUser();
	try {
		for (UserHistory<Event> evt: stream) {
			MutableSparseVector vector = RatingVectorUserHistorySummarizer.makeRatingVector(evt).mutableCopy();
			// vector is now the user's rating vector
			// Normalize this vector
			vector.add(-vector.mean());
			// Store the ratings in the item data
			for (VectorEntry vectorEntry : vector.fast(VectorEntry.State.EITHER)) {
				long itemId = vectorEntry.getKey();
				double rating = vectorEntry.getValue();
				long userId = evt.getUserId();
				itemData.get(itemId).put(userId, rating);
			}
		}
	} finally {
		stream.close();
	}

	// This loop converts our temporary item storage to a map of item vectors
	Map<Long,ImmutableSparseVector> itemVectors = new HashMap<Long, ImmutableSparseVector>();
	for (Map.Entry<Long,Map<Long,Double>> entry: itemData.entrySet()) {
		MutableSparseVector vec = MutableSparseVector.create(entry.getValue());
		itemVectors.put(entry.getKey(), vec.immutable());
	}
	return itemVectors;
}
 
开发者ID:paolobarbaglia,项目名称:coursera_recommender_systems,代码行数:44,代码来源:SimpleItemItemModelBuilder.java

示例10: createRatingMatrix

import org.grouplens.lenskit.vectors.MutableSparseVector; //导入方法依赖的package包/类
/**
 * Build a rating matrix from the rating data.  Each user's ratings are first normalized
 * by subtracting a baseline score (usually a mean).
 *
 * @param userMapping The index mapping of user IDs to column numbers.
 * @param itemMapping The index mapping of item IDs to row numbers.
 * @return A matrix storing the <i>normalized</i> user ratings.
 */
private RealMatrix createRatingMatrix(IdIndexMapping userMapping, IdIndexMapping itemMapping) {
    final int nusers = userMapping.size();
    final int nitems = itemMapping.size();

    // Create a matrix with users on rows and items on columns
    logger.info("creating {} by {} rating matrix", nusers, nitems);
    RealMatrix matrix = MatrixUtils.createRealMatrix(nusers, nitems);

    // populate it with data
    Cursor<UserHistory<Event>> users = userEventDAO.streamEventsByUser();
    try {
        for (UserHistory<Event> user: users) {
            // Get the row number for this user
            int u = userMapping.getIndex(user.getUserId());
            MutableSparseVector ratings = Ratings.userRatingVector(user.filter(Rating.class));
            MutableSparseVector baselines = MutableSparseVector.create(ratings.keySet());
            baselineScorer.score(user.getUserId(), baselines);
            
            for(VectorEntry v : ratings.fast())
            {
            	matrix.setEntry(u, itemMapping.getIndex(v.getKey()), v.getValue() - baselineScorer.score(user.getUserId(), v.getKey()));
            }
            
        }
    } finally {
        users.close();
    }

    return matrix;
}
 
开发者ID:paolobarbaglia,项目名称:coursera_recommender_systems,代码行数:39,代码来源:SVDModelBuilder.java

示例11: entropy

import org.grouplens.lenskit.vectors.MutableSparseVector; //导入方法依赖的package包/类
private double entropy(TagVocabulary vocab, ItemTagDAO tagDAO, List<ScoredId> recommendations) {
    MutableSparseVector tagProbs = tagProbabilities(vocab, tagDAO, recommendations);
    MutableSparseVector logProbs = MutableSparseVector.create(tagProbs.keyDomain());
    for (VectorEntry entry : logProbs.fast(State.UNSET)) {
        long tagid = entry.getKey();
        double probability = tagProbs.get(tagid);
        double logprob = Math.log(probability) / Math.log(2);
        logProbs.set(entry, logprob);
    }
    return -1.0 * logProbs.dot(tagProbs);
}
 
开发者ID:paolobarbaglia,项目名称:coursera_recommender_systems,代码行数:12,代码来源:TagEntropyMetric.java


注:本文中的org.grouplens.lenskit.vectors.MutableSparseVector.fast方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。