List of usage examples for org.apache.mahout.cf.taste.common NoSuchItemException NoSuchItemException
public NoSuchItemException(String message)
From source file:net.myrrix.client.ClientRecommender.java
License:Apache License
public float estimateForAnonymous(long toItemID, long[] itemIDs, float[] values, Long contextUserID) throws TasteException { Preconditions.checkArgument(values == null || values.length == itemIDs.length, "Number of values doesn't match number of items"); StringBuilder urlPath = new StringBuilder(32); urlPath.append("/estimateForAnonymous/"); urlPath.append(toItemID);/*w w w . j a v a 2s. c om*/ for (int i = 0; i < itemIDs.length; i++) { urlPath.append('/').append(itemIDs[i]); if (values != null) { urlPath.append('=').append(values[i]); } } // Requests are typically partitioned by user, but this request does not directly depend on a user. // If a user ID is supplied anyway, use it for partitioning since it will follow routing for other // requests related to that user. Otherwise just partition on the "to" item ID, which is at least // deterministic. long idToPartitionOn = contextUserID == null ? toItemID : contextUserID; TasteException savedException = null; for (HostAndPort replica : choosePartitionAndReplicas(idToPartitionOn)) { HttpURLConnection connection = null; try { connection = buildConnectionToReplica(replica, urlPath.toString(), "GET"); switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: BufferedReader reader = IOUtils.bufferStream(connection.getInputStream()); try { return LangUtils.parseFloat(reader.readLine()); } finally { Closeables.close(reader, true); } case HttpURLConnection.HTTP_NOT_FOUND: throw new NoSuchItemException(Arrays.toString(itemIDs) + ' ' + toItemID); case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (TasteException te) { log.info("Can't access {} at {}: ({})", urlPath, replica, te.toString()); savedException = te; } catch (IOException ioe) { log.info("Can't access {} at {}: ({})", urlPath, replica, ioe.toString()); savedException = new TasteException(ioe); } finally { if (connection != null) { connection.disconnect(); } } } throw savedException; }
From source file:net.myrrix.client.ClientRecommender.java
License:Apache License
private List<RecommendedItem> anonymousOrSimilar(long[] itemIDs, float[] values, int howMany, String path, String[] rescorerParams, Long contextUserID) throws TasteException { Preconditions.checkArgument(values == null || values.length == itemIDs.length, "Number of values doesn't match number of items"); StringBuilder urlPath = new StringBuilder(); urlPath.append(path);/*ww w .ja v a 2 s.c om*/ for (int i = 0; i < itemIDs.length; i++) { urlPath.append('/').append(itemIDs[i]); if (values != null) { urlPath.append('=').append(values[i]); } } appendCommonQueryParams(howMany, false, rescorerParams, urlPath); // Requests are typically partitioned by user, but this request does not directly depend on a user. // If a user ID is supplied anyway, use it for partitioning since it will follow routing for other // requests related to that user. Otherwise just partition on (first0 item ID, which is at least // deterministic. long idToPartitionOn = contextUserID == null ? itemIDs[0] : contextUserID; TasteException savedException = null; for (HostAndPort replica : choosePartitionAndReplicas(idToPartitionOn)) { HttpURLConnection connection = null; try { connection = buildConnectionToReplica(replica, urlPath.toString(), "GET"); switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: return consumeItems(connection); case HttpURLConnection.HTTP_NOT_FOUND: throw new NoSuchItemException(Arrays.toString(itemIDs)); case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (TasteException te) { log.info("Can't access {} at {}: ({})", urlPath, replica, te.toString()); savedException = te; } catch (IOException ioe) { log.info("Can't access {} at {}: ({})", urlPath, replica, ioe.toString()); savedException = new TasteException(ioe); } finally { if (connection != null) { connection.disconnect(); } } } throw savedException; }
From source file:net.myrrix.client.ClientRecommender.java
License:Apache License
/** * Like {@link #similarityToItem(long, long[])}, but allows caller to specify the user for which the request * is being made. This information does not directly affect the computation, but affects <em>routing</em> * of the request in a distributed context. This is always recommended when there is a user in whose context * the request is being made, as it will ensure that the request can take into account all the latest information * from the user, including very new items that may be in {@code itemIDs}. *///from w ww. j a v a 2s . c o m public float[] similarityToItem(long toItemID, long[] itemIDs, Long contextUserID) throws TasteException { StringBuilder urlPath = new StringBuilder(32); urlPath.append("/similarityToItem/"); urlPath.append(toItemID); for (long itemID : itemIDs) { urlPath.append('/').append(itemID); } // Requests are typically partitioned by user, but this request does not directly depend on a user. // If a user ID is supplied anyway, use it for partitioning since it will follow routing for other // requests related to that user. Otherwise just partition on (first0 item ID, which is at least // deterministic. long idToPartitionOn = contextUserID == null ? itemIDs[0] : contextUserID; TasteException savedException = null; for (HostAndPort replica : choosePartitionAndReplicas(idToPartitionOn)) { HttpURLConnection connection = null; try { connection = buildConnectionToReplica(replica, urlPath.toString(), "GET"); switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: BufferedReader reader = IOUtils.bufferStream(connection.getInputStream()); try { float[] result = new float[itemIDs.length]; for (int i = 0; i < itemIDs.length; i++) { result[i] = LangUtils.parseFloat(reader.readLine()); } return result; } finally { Closeables.close(reader, true); } case HttpURLConnection.HTTP_NOT_FOUND: throw new NoSuchItemException(connection.getResponseMessage()); case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (TasteException te) { log.info("Can't access {} at {}: ({})", urlPath, replica, te.toString()); savedException = te; } catch (IOException ioe) { log.info("Can't access {} at {}: ({})", urlPath, replica, ioe.toString()); savedException = new TasteException(ioe); } finally { if (connection != null) { connection.disconnect(); } } } throw savedException; }
From source file:net.myrrix.client.ClientRecommender.java
License:Apache License
/** * <p>Lists the items that were most influential in recommending a given item to a given user. Exactly how this * is determined is left to the implementation, but, generally this will return items that the user prefers * and that are similar to the given item.</p> * * <p>These values by which the results are ordered are opaque values and have no interpretation * other than that larger means stronger.</p> * * @param userID ID of user who was recommended the item * @param itemID ID of item that was recommended * @param howMany maximum number of items to return * @return {@link List} of {@link RecommendedItem}, ordered from most influential in recommended the given * item to least// w w w . j a va2 s .co m * @throws NoSuchUserException if the user is not known in the model * @throws NoSuchItemException if the item is not known in the model * @throws NotReadyException if the recommender has no model available yet * @throws TasteException if another error occurs */ @Override public List<RecommendedItem> recommendedBecause(long userID, long itemID, int howMany) throws TasteException { String urlPath = "/because/" + userID + '/' + itemID + "?howMany=" + howMany; TasteException savedException = null; for (HostAndPort replica : choosePartitionAndReplicas(userID)) { HttpURLConnection connection = null; try { connection = buildConnectionToReplica(replica, urlPath, "GET"); switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: return consumeItems(connection); case HttpURLConnection.HTTP_NOT_FOUND: String connectionMessage = connection.getResponseMessage(); if (connectionMessage != null && connectionMessage.contains(NoSuchUserException.class.getSimpleName())) { throw new NoSuchUserException(userID); } else { throw new NoSuchItemException(itemID); } case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (TasteException te) { log.info("Can't access {} at {}: ({})", urlPath, replica, te.toString()); savedException = te; } catch (IOException ioe) { log.info("Can't access {} at {}: ({})", urlPath, replica, ioe.toString()); savedException = new TasteException(ioe); } finally { if (connection != null) { connection.disconnect(); } } } throw savedException; }
From source file:net.myrrix.online.ServerRecommender.java
License:Apache License
private float[] buildAnonymousUserFeatures(long[] itemIDs, float[] values) throws NotReadyException, NoSuchItemException { Preconditions.checkArgument(values == null || values.length == itemIDs.length, "Number of values doesn't match number of items"); Generation generation = getCurrentGeneration(); FastByIDMap<float[]> Y = generation.getY(); Solver ytySolver = generation.getYTYSolver(); if (ytySolver == null) { throw new NotReadyException(); }/* www. j ava2 s. co m*/ float[] anonymousUserFeatures = null; Lock yLock = generation.getYLock().readLock(); boolean anyItemIDFound = false; for (int j = 0; j < itemIDs.length; j++) { long itemID = itemIDs[j]; float[] itemFeatures; yLock.lock(); try { itemFeatures = Y.get(itemID); } finally { yLock.unlock(); } if (itemFeatures == null) { continue; } anyItemIDFound = true; double[] userFoldIn = ytySolver.solveFToD(itemFeatures); if (anonymousUserFeatures == null) { anonymousUserFeatures = new float[userFoldIn.length]; } double signedFoldInWeight = foldInWeight(0.0, values == null ? 1.0f : values[j]); if (signedFoldInWeight != 0.0) { for (int i = 0; i < anonymousUserFeatures.length; i++) { anonymousUserFeatures[i] += (float) (signedFoldInWeight * userFoldIn[i]); } } } if (!anyItemIDFound) { throw new NoSuchItemException(Arrays.toString(itemIDs)); } return anonymousUserFeatures; }
From source file:net.myrrix.online.ServerRecommender.java
License:Apache License
@Override public float estimateForAnonymous(long toItemID, long[] itemIDs, float[] values) throws NotReadyException, NoSuchItemException { Generation generation = getCurrentGeneration(); FastByIDMap<float[]> Y = generation.getY(); Lock yLock = generation.getYLock().readLock(); float[] toItemFeatures; yLock.lock();/* w w w .ja v a2 s.c om*/ try { toItemFeatures = Y.get(toItemID); } finally { yLock.unlock(); } if (toItemFeatures == null) { throw new NoSuchItemException(toItemID); } float[] anonymousUserFeatures = buildAnonymousUserFeatures(itemIDs, values); return (float) SimpleVectorMath.dot(anonymousUserFeatures, toItemFeatures); }
From source file:net.myrrix.online.ServerRecommender.java
License:Apache License
/** * One-argument version of {@link #mostSimilarItems(long[], int, Rescorer)}. *///from w ww. jav a 2 s . c o m @Override public List<RecommendedItem> mostSimilarItems(long itemID, int howMany, Rescorer<LongPair> rescorer) throws NoSuchItemException, NotReadyException { Preconditions.checkArgument(howMany > 0, "howMany must be positive"); Generation generation = getCurrentGeneration(); FastByIDMap<float[]> Y = generation.getY(); Lock yLock = generation.getYLock().readLock(); yLock.lock(); try { float[] itemFeatures = Y.get(itemID); if (itemFeatures == null) { throw new NoSuchItemException(itemID); } return TopN.selectTopN(new MostSimilarItemIterator(Y.entrySet().iterator(), generation.getUserTagIDs(), new long[] { itemID }, new float[][] { itemFeatures }, rescorer), howMany); } finally { yLock.unlock(); } }
From source file:net.myrrix.online.ServerRecommender.java
License:Apache License
/** * Computes items most similar to an item or items. The returned items have the highest average similarity * to the given items./*from w ww.j a va 2 s . co m*/ * * @param itemIDs items for which most similar items are required * @param howMany maximum number of similar items to return; fewer may be returned * @param rescorer rescoring function used to modify item-item similarities before ranking results * @return {@link RecommendedItem}s representing the top recommendations for the user, ordered by quality, * descending. The score associated to it is an opaque value. Larger means more similar, but no further * interpretation may necessarily be applied. * @throws NoSuchItemException if any of the items is not known in the model * @throws NotReadyException if the recommender has no model available yet */ @Override public List<RecommendedItem> mostSimilarItems(long[] itemIDs, int howMany, Rescorer<LongPair> rescorer) throws NoSuchItemException, NotReadyException { Preconditions.checkArgument(howMany > 0, "howMany must be positive"); Generation generation = getCurrentGeneration(); FastByIDMap<float[]> Y = generation.getY(); Lock yLock = generation.getYLock().readLock(); yLock.lock(); try { List<float[]> itemFeatures = Lists.newArrayListWithCapacity(itemIDs.length); for (long itemID : itemIDs) { float[] features = Y.get(itemID); if (features != null) { itemFeatures.add(features); } } if (itemFeatures.isEmpty()) { throw new NoSuchItemException(Arrays.toString(itemIDs)); } float[][] itemFeaturesArray = itemFeatures.toArray(new float[itemFeatures.size()][]); return TopN.selectTopN(new MostSimilarItemIterator(Y.entrySet().iterator(), generation.getUserTagIDs(), itemIDs, itemFeaturesArray, rescorer), howMany); } finally { yLock.unlock(); } }
From source file:net.myrrix.online.ServerRecommender.java
License:Apache License
@Override public float[] similarityToItem(long toItemID, long... itemIDs) throws TasteException { Generation generation = getCurrentGeneration(); FastByIDMap<float[]> Y = generation.getY(); float[] similarities = new float[itemIDs.length]; Lock yLock = generation.getYLock().readLock(); yLock.lock();//from ww w.j av a2 s . com try { float[] toFeatures = Y.get(toItemID); if (toFeatures == null) { throw new NoSuchItemException(toItemID); } double toFeaturesNorm = SimpleVectorMath.norm(toFeatures); boolean anyFound = false; for (int i = 0; i < similarities.length; i++) { float[] features = Y.get(itemIDs[i]); if (features == null) { similarities[i] = Float.NaN; } else { anyFound = true; double featuresNorm = SimpleVectorMath.norm(features); similarities[i] = (float) (SimpleVectorMath.dot(features, toFeatures) / (featuresNorm * toFeaturesNorm)); } } if (!anyFound) { throw new NoSuchItemException(Arrays.toString(itemIDs)); } } finally { yLock.unlock(); } return similarities; }
From source file:net.myrrix.online.ServerRecommender.java
License:Apache License
/** * <p>Lists the items that were most influential in recommending a given item to a given user. Exactly how this * is determined is left to the implementation, but, generally this will return items that the user prefers * and that are similar to the given item.</p> * * <p>These values by which the results are ordered are opaque values and have no interpretation * other than that larger means stronger.</p> * * @param userID ID of user who was recommended the item * @param itemID ID of item that was recommended * @param howMany maximum number of items to return * @return {@link List} of {@link RecommendedItem}, ordered from most influential in recommended the given * item to least//from w w w . j a v a 2 s.c o m * @throws NoSuchUserException if the user is not known in the model * @throws NoSuchItemException if the item is not known in the model * @throws NotReadyException if the recommender has no model available yet */ @Override public List<RecommendedItem> recommendedBecause(long userID, long itemID, int howMany) throws NoSuchUserException, NoSuchItemException, NotReadyException { Preconditions.checkArgument(howMany > 0, "howMany must be positive"); Generation generation = getCurrentGeneration(); FastByIDMap<FastIDSet> knownItemIDs = generation.getKnownItemIDs(); if (knownItemIDs == null) { throw new UnsupportedOperationException("No known item IDs available"); } Lock knownItemLock = generation.getKnownItemLock().readLock(); FastIDSet userKnownItemIDs; knownItemLock.lock(); try { userKnownItemIDs = knownItemIDs.get(userID); } finally { knownItemLock.unlock(); } if (userKnownItemIDs == null) { throw new NoSuchUserException(userID); } FastByIDMap<float[]> Y = generation.getY(); Lock yLock = generation.getYLock().readLock(); yLock.lock(); try { float[] features = Y.get(itemID); if (features == null) { throw new NoSuchItemException(itemID); } FastByIDMap<float[]> toFeatures; synchronized (userKnownItemIDs) { toFeatures = new FastByIDMap<float[]>(userKnownItemIDs.size(), 1.25f); LongPrimitiveIterator it = userKnownItemIDs.iterator(); while (it.hasNext()) { long fromItemID = it.nextLong(); float[] fromFeatures = Y.get(fromItemID); toFeatures.put(fromItemID, fromFeatures); } } return TopN.selectTopN(new RecommendedBecauseIterator(toFeatures.entrySet().iterator(), generation.getUserTagIDs(), features), howMany); } finally { yLock.unlock(); } }