Package org.grouplens.lenskit.vectors

Examples of org.grouplens.lenskit.vectors.MutableSparseVector


        }
        @Override
        protected Neighbor computeNext() {
            while (neighborIter.hasNext()) {
                final long neighbor = neighborIter.nextLong();
                MutableSparseVector nbrRatings = getUserRatingVector(neighbor);
                if (nbrRatings != null) {
                    ImmutableSparseVector rawRatings = nbrRatings.immutable();
                    normalizer.normalize(neighbor, rawRatings, nbrRatings);
                    final double sim = similarity.similarity(user, userVector, neighbor, nbrRatings);
                    if (acceptSimilarity(sim)) {
                        // we have found a neighbor
                        return new Neighbor(neighbor, rawRatings, sim);
View Full Code Here


                           MutableSparseVector scores,
                           NeighborhoodScorer scorer) {
        Predicate<ScoredId> usable = new VectorKeyPredicate(userData);

        // Create a channel for recording the neighborhoodsize
        MutableSparseVector sizeChannel = scores.getOrAddChannelVector(ItemItemScorer.NEIGHBORHOOD_SIZE_SYMBOL);
        sizeChannel.fill(0);
        // for each item, compute its prediction
        for (VectorEntry e : scores.view(VectorEntry.State.EITHER)) {
            final long item = e.getKey();

            // find all potential neighbors
            FluentIterable<ScoredId> nbrIter = FluentIterable.from(model.getNeighbors(item))
                                                             .filter(usable);
            if (neighborhoodSize > 0) {
                nbrIter = nbrIter.limit(neighborhoodSize);
            }
            List<ScoredId> neighbors = nbrIter.toList();

            // compute score & place in vector
            ScoredId score = null;

            if (neighbors.size() >= minNeighbors) {
                score = scorer.score(item, neighbors, userData);
            }

            if (score != null) {
                scores.set(e, score.getScore());
                // FIXME Scorers should not need to do this.
                for (TypedSymbol sym: score.getChannelSymbols()) {
                    scores.getOrAddChannel(sym).put(e.getKey(), score.getChannelValue(sym));
                }
            }

            sizeChannel.set(e, neighbors.size());
        }
    }
View Full Code Here

    @Override
    public void globalScore(@Nonnull Collection<Long> queryItems,
                            @Nonnull MutableSparseVector output) {
        // create the unary rating for the items
        LongSortedSet qItems = LongUtils.packedSet(queryItems);
        MutableSparseVector basket = MutableSparseVector.create(qItems, 1.0);

        output.clear();
        algorithm.scoreItems(model, basket, output, scorer);
    }
View Full Code Here

        assert itemDomain.size() == itemDomain.domainSize();
        assert itemDomain.domainSize() == nitems;
        List<List<ScoredId>> matrix = Lists.newArrayListWithCapacity(itemDomain.domainSize());

        // working space for accumulating each row (reuse between rows)
        MutableSparseVector currentRow = MutableSparseVector.create(itemUniverse);
        Stopwatch timer = Stopwatch.createStarted();

        for (int i = 0; i < nitems; i++) {
            assert matrix.size() == i;
            final long rowItem = itemDomain.getKey(i);
            final SparseVector vec1 = buildContext.itemVector(rowItem);

            // Take advantage of sparsity if we can
            LongIterator neighbors = iterationStrategy.neighborIterator(buildContext, rowItem, false);
            currentRow.fill(0);

            // Compute similarities and populate the vector
            while (neighbors.hasNext()) {
                final long colItem = neighbors.nextLong();
                final SparseVector vec2 = buildContext.itemVector(colItem);
                assert currentRow.containsKey(colItem);
                currentRow.set(colItem, similarity.similarity(rowItem, vec1, colItem, vec2));
            }

            // Remove the current item (it is not its own neighbor)
            currentRow.unset(rowItem);

            // Normalize and truncate the row
            MutableSparseVector normalized = rowNormalizer.normalize(rowItem, currentRow, null);
            truncator.truncate(normalized);

            // Build up and save the row
            ScoredIdListBuilder bld = new ScoredIdListBuilder(normalized.size());
            // TODO Allow the symbols in use to be customized
            List<ScoredId> row = bld.addChannels(normalized.getChannelVectorSymbols())
                                    .addTypedChannels(normalized.getChannelSymbols())
                                    .addAll(ScoredIds.collectionFromVector(normalized))
                                    .sort(ScoredIds.scoreOrder().reverse())
                                    .finish();
            matrix.add(row);
        }
View Full Code Here

        Cursor<UserHistory<Event>> users = userEventDAO.streamEventsByUser();
        try {
            for (UserHistory<Event> user : users) {
                long uid = user.getUserId();
                SparseVector summary = userSummarizer.summarize(user);
                MutableSparseVector normed = summary.mutableCopy();
                normalizer.normalize(uid, summary, normed);

                for (VectorEntry rating : normed) {
                    final long item = rating.getKey();
                    // get the item's rating accumulator
View Full Code Here

     *
     * @return A sparse vector containing the data accumulated.
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public ImmutableSparseVector buildVector() {
        MutableSparseVector msv = MutableSparseVector.create(ids);
        final int size = size();
        for (int i = 0; i < size; i++) {
            msv.set(ids.get(i), scores.get(i));
        }

        for (ChannelStorage chan: channels.values()) {
            MutableSparseVector vchan = msv.getOrAddChannelVector(chan.symbol);
            for (int i = 0; i < size; i++) {
                vchan.set(ids.get(i), chan.values.get(i));
            }
        }

        for (TypedChannelStorage<?> chan: typedChannels.values()) {
            Long2ObjectMap vchan = msv.getOrAddChannel(chan.symbol);
            for (int i = 0; i < size; i++) {
                vchan.put(ids.get(i), chan.values.get(i));
            }
        }

        return msv.freeze();
    }
View Full Code Here

            }

            logger.info("trained baseline on {} ratings in {} iterations (final rmse={})", ratings.size(), trainingController.getIterationCount(), rmse);

            // Convert the uoff array to a SparseVector
            MutableSparseVector svuoff = Vectors.fromArray(snapshot.userIndex(), uoff);
            // Convert the ioff array to a SparseVector
            MutableSparseVector svioff = Vectors.fromArray(snapshot.itemIndex(), ioff);
            return new LeastSquaresItemScorer(svuoff.freeze(), svioff.freeze(), mean);
        }
View Full Code Here

    public void score(long user, @Nonnull MutableSparseVector output) {
        primaryScorer.score(user, output);
        LongSet fallbackKeys = LongSets.EMPTY_SET;
        if (output.size() != output.keyDomain().size()) {
            fallbackKeys = output.unsetKeySet();
            MutableSparseVector blpreds = MutableSparseVector.create(fallbackKeys);
            baselineScorer.score(user, blpreds);
            output.set(blpreds);
        }

        // FIXME Make this faster
View Full Code Here

            return Double.NaN;
        }

        LongSet ts = LongUtils.setUnion(vec1.keySet(),vec2.keySet());

        MutableSparseVector v1 = MutableSparseVector.create(ts);
        v1.fill(0);
        v1.set(vec1);
        v1.multiply(1.0 / v1.norm());
        v1.addScaled(vec2, -1.0 / vec2.norm());

        distance = v1.norm();
        return 1-distance;
    }
View Full Code Here

    public void score(long user, @Nonnull MutableSparseVector items) {
        UserHistory<?> history = userEventDAO.getEventsForUser(user, summarizer.eventTypeWanted());
        if (history == null) {
            baseline.score(user, items);
        } else {
            MutableSparseVector vec = summarizer.summarize(history).mutableCopy();
            // score everything, both rated and not, for offsets
            LongSet allItems = LongUtils.setUnion(vec.keySet(), items.keyDomain());
            MutableSparseVector baseScores = MutableSparseVector.create(allItems);
            baseline.score(user, baseScores);
            // subtract scores from ratings, yielding offsets
            vec.subtract(baseScores);
            double meanOffset = vec.sum() / (vec.size() + damping);
            // to score: fill with baselines, add user mean offset
View Full Code Here

TOP

Related Classes of org.grouplens.lenskit.vectors.MutableSparseVector

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.