You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mahout.apache.org by ro...@apache.org on 2010/02/13 21:54:31 UTC
svn commit: r909912 [9/10] - in
/lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste: common/
eval/ hadoop/ hadoop/cooccurence/ hadoop/item/ hadoop/pseudo/
hadoop/slopeone/ impl/common/ impl/common/jdbc/ impl/eval/ impl/model/
impl/model/...
Modified: lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/CachingUserSimilarity.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/CachingUserSimilarity.java?rev=909912&r1=909911&r2=909912&view=diff
==============================================================================
--- lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/CachingUserSimilarity.java (original)
+++ lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/CachingUserSimilarity.java Sat Feb 13 20:54:05 2010
@@ -17,63 +17,66 @@
package org.apache.mahout.cf.taste.impl.similarity;
+import java.util.Collection;
+
import org.apache.mahout.cf.taste.common.Refreshable;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.Cache;
-import org.apache.mahout.common.LongPair;
import org.apache.mahout.cf.taste.impl.common.RefreshHelper;
import org.apache.mahout.cf.taste.impl.common.Retriever;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.similarity.PreferenceInferrer;
import org.apache.mahout.cf.taste.similarity.UserSimilarity;
+import org.apache.mahout.common.LongPair;
-import java.util.Collection;
-
-/** Caches the results from an underlying {@link org.apache.mahout.cf.taste.similarity.UserSimilarity} implementation. */
+/**
+ * Caches the results from an underlying {@link org.apache.mahout.cf.taste.similarity.UserSimilarity}
+ * implementation.
+ */
public final class CachingUserSimilarity implements UserSimilarity {
-
+
private final UserSimilarity similarity;
- private final Cache<LongPair, Double> similarityCache;
-
+ private final Cache<LongPair,Double> similarityCache;
+
public CachingUserSimilarity(UserSimilarity similarity, DataModel dataModel) throws TasteException {
if (similarity == null) {
throw new IllegalArgumentException("similarity is null");
}
this.similarity = similarity;
- int maxCacheSize = dataModel.getNumUsers(); // just a dumb heuristic for sizing
- this.similarityCache = new Cache<LongPair, Double>(new SimilarityRetriever(similarity), maxCacheSize);
+ int maxCacheSize = dataModel.getNumUsers(); // just a dumb heuristic for sizing
+ this.similarityCache = new Cache<LongPair,Double>(new SimilarityRetriever(similarity), maxCacheSize);
}
-
+
@Override
public double userSimilarity(long userID1, long userID2) throws TasteException {
LongPair key = userID1 < userID2 ? new LongPair(userID1, userID2) : new LongPair(userID2, userID1);
return similarityCache.get(key);
}
-
+
@Override
public void setPreferenceInferrer(PreferenceInferrer inferrer) {
similarityCache.clear();
similarity.setPreferenceInferrer(inferrer);
}
-
+
@Override
public void refresh(Collection<Refreshable> alreadyRefreshed) {
similarityCache.clear();
alreadyRefreshed = RefreshHelper.buildRefreshed(alreadyRefreshed);
RefreshHelper.maybeRefresh(alreadyRefreshed, similarity);
}
-
- private static final class SimilarityRetriever implements Retriever<LongPair, Double> {
+
+ private static final class SimilarityRetriever implements Retriever<LongPair,Double> {
private final UserSimilarity similarity;
-
+
private SimilarityRetriever(UserSimilarity similarity) {
this.similarity = similarity;
}
-
+
@Override
public Double get(LongPair key) throws TasteException {
return similarity.userSimilarity(key.getFirst(), key.getSecond());
}
}
-
+
}
Modified: lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/EuclideanDistanceSimilarity.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/EuclideanDistanceSimilarity.java?rev=909912&r1=909911&r2=909912&view=diff
==============================================================================
--- lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/EuclideanDistanceSimilarity.java (original)
+++ lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/EuclideanDistanceSimilarity.java Sat Feb 13 20:54:05 2010
@@ -22,23 +22,24 @@
import org.apache.mahout.cf.taste.model.DataModel;
/**
- * <p>An implementation of a "similarity" based on the Euclidean "distance" between two
- * users X and Y. Thinking of items as dimensions and preferences as points along
- * those dimensions, a distance is computed using all items (dimensions) where both users have expressed a preference
- * for that item. This is simply the square root of the sum of the squares of differences in position (preference) along
- * each dimension. The similarity is then computed as 1 / (1 + distance), so the resulting values are in the range
- * (0,1].</p>
+ * <p>
+ * An implementation of a "similarity" based on the Euclidean "distance" between two users X and Y. Thinking
+ * of items as dimensions and preferences as points along those dimensions, a distance is computed using all
+ * items (dimensions) where both users have expressed a preference for that item. This is simply the square
+ * root of the sum of the squares of differences in position (preference) along each dimension. The similarity
+ * is then computed as 1 / (1 + distance), so the resulting values are in the range (0,1].
+ * </p>
*/
public final class EuclideanDistanceSimilarity extends AbstractSimilarity {
-
+
public EuclideanDistanceSimilarity(DataModel dataModel) throws TasteException {
super(dataModel);
}
-
+
public EuclideanDistanceSimilarity(DataModel dataModel, Weighting weighting) throws TasteException {
super(dataModel, weighting);
}
-
+
@Override
double computeResult(int n, double sumXY, double sumX2, double sumY2, double sumXYdiff2) {
if (n == 0) {
@@ -51,7 +52,7 @@
// normalize a bit for magnitude
sumXYdiff2 /= denominator;
// divide by n below to not automatically give users with more overlap more similarity
- return 1.0 / (1.0 + (Math.sqrt(sumXYdiff2) / (double) n));
+ return 1.0 / (1.0 + Math.sqrt(sumXYdiff2) / n);
}
-
+
}
\ No newline at end of file
Modified: lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/GenericItemSimilarity.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/GenericItemSimilarity.java?rev=909912&r1=909911&r2=909912&view=diff
==============================================================================
--- lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/GenericItemSimilarity.java (original)
+++ lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/GenericItemSimilarity.java Sat Feb 13 20:54:05 2010
@@ -17,103 +17,133 @@
package org.apache.mahout.cf.taste.impl.similarity;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+
import org.apache.mahout.cf.taste.common.Refreshable;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.FastByIDMap;
-import org.apache.mahout.common.iterator.IteratorIterable;
-import org.apache.mahout.common.iterator.IteratorUtils;
-import org.apache.mahout.common.RandomUtils;
import org.apache.mahout.cf.taste.impl.recommender.TopItems;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.similarity.ItemSimilarity;
-
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.NoSuchElementException;
+import org.apache.mahout.common.RandomUtils;
+import org.apache.mahout.common.iterator.IteratorIterable;
+import org.apache.mahout.common.iterator.IteratorUtils;
/**
- * <p>A "generic" {@link ItemSimilarity} which takes a static list of precomputed item similarities and bases
- * its responses on that alone. The values may have been precomputed offline by another process, stored in a file, and
- * then read and fed into an instance of this class.</p>
- *
- * <p>This is perhaps the best {@link ItemSimilarity} to use with {@link org.apache.mahout.cf.taste.impl.recommender.GenericItemBasedRecommender},
- * for now, since the point of item-based recommenders is that they can take advantage of the fact that item similarity
- * is relatively static, can be precomputed, and then used in computation to gain a significant performance
- * advantage.</p>
+ * <p>
+ * A "generic" {@link ItemSimilarity} which takes a static list of precomputed item similarities and bases its
+ * responses on that alone. The values may have been precomputed offline by another process, stored in a file,
+ * and then read and fed into an instance of this class.
+ * </p>
+ *
+ * <p>
+ * This is perhaps the best {@link ItemSimilarity} to use with
+ * {@link org.apache.mahout.cf.taste.impl.recommender.GenericItemBasedRecommender}, for now, since the point
+ * of item-based recommenders is that they can take advantage of the fact that item similarity is relatively
+ * static, can be precomputed, and then used in computation to gain a significant performance advantage.
+ * </p>
*/
public final class GenericItemSimilarity implements ItemSimilarity {
-
+
private final FastByIDMap<FastByIDMap<Double>> similarityMaps = new FastByIDMap<FastByIDMap<Double>>();
-
+
/**
- * <p>Creates a {@link GenericItemSimilarity} from a precomputed list of {@link ItemItemSimilarity}s. Each represents
- * the similarity between two distinct items. Since similarity is assumed to be symmetric, it is not necessary to
- * specify similarity between item1 and item2, and item2 and item1. Both are the same. It is also not necessary to
- * specify a similarity between any item and itself; these are assumed to be 1.0.</p>
- *
- * <p>Note that specifying a similarity between two items twice is not an error, but, the later value will win.</p>
- *
- * @param similarities set of {@link ItemItemSimilarity}s on which to base this instance
+ * <p>
+ * Creates a {@link GenericItemSimilarity} from a precomputed list of {@link ItemItemSimilarity}s. Each
+ * represents the similarity between two distinct items. Since similarity is assumed to be symmetric, it is
+ * not necessary to specify similarity between item1 and item2, and item2 and item1. Both are the same. It
+ * is also not necessary to specify a similarity between any item and itself; these are assumed to be 1.0.
+ * </p>
+ *
+ * <p>
+ * Note that specifying a similarity between two items twice is not an error, but, the later value will win.
+ * </p>
+ *
+ * @param similarities
+ * set of {@link ItemItemSimilarity}s on which to base this instance
*/
public GenericItemSimilarity(Iterable<ItemItemSimilarity> similarities) {
initSimilarityMaps(similarities);
}
-
+
/**
- * <p>Like {@link #GenericItemSimilarity(Iterable)}, but will only keep the specified number of similarities from the
- * given {@link Iterable} of similarities. It will keep those with the highest similarity -- those that are therefore
- * most important.</p>
- *
- * <p>Thanks to tsmorton for suggesting this and providing part of the implementation.</p>
- *
- * @param similarities set of {@link ItemItemSimilarity}s on which to base this instance
- * @param maxToKeep maximum number of similarities to keep
+ * <p>
+ * Like {@link #GenericItemSimilarity(Iterable)}, but will only keep the specified number of similarities
+ * from the given {@link Iterable} of similarities. It will keep those with the highest similarity -- those
+ * that are therefore most important.
+ * </p>
+ *
+ * <p>
+ * Thanks to tsmorton for suggesting this and providing part of the implementation.
+ * </p>
+ *
+ * @param similarities
+ * set of {@link ItemItemSimilarity}s on which to base this instance
+ * @param maxToKeep
+ * maximum number of similarities to keep
*/
public GenericItemSimilarity(Iterable<ItemItemSimilarity> similarities, int maxToKeep) {
- Iterable<ItemItemSimilarity> keptSimilarities = TopItems.getTopItemItemSimilarities(maxToKeep, similarities);
+ Iterable<ItemItemSimilarity> keptSimilarities = TopItems.getTopItemItemSimilarities(maxToKeep,
+ similarities);
initSimilarityMaps(keptSimilarities);
}
-
+
/**
- * <p>Builds a list of item-item similarities given an {@link ItemSimilarity} implementation and a {@link DataModel},
- * rather than a list of {@link ItemItemSimilarity}s.</p>
- *
- * <p>It's valid to build a {@link GenericItemSimilarity} this way, but perhaps missing some of the point of an
- * item-based recommender. Item-based recommenders use the assumption that item-item similarities are relatively
- * fixed, and might be known already independent of user preferences. Hence it is useful to inject that information,
- * using {@link #GenericItemSimilarity(Iterable)}.</p>
- *
- * @param otherSimilarity other {@link ItemSimilarity} to get similarities from
- * @param dataModel data model to get items from
- * @throws TasteException if an error occurs while accessing the {@link DataModel} items
+ * <p>
+ * Builds a list of item-item similarities given an {@link ItemSimilarity} implementation and a
+ * {@link DataModel}, rather than a list of {@link ItemItemSimilarity}s.
+ * </p>
+ *
+ * <p>
+ * It's valid to build a {@link GenericItemSimilarity} this way, but perhaps missing some of the point of an
+ * item-based recommender. Item-based recommenders use the assumption that item-item similarities are
+ * relatively fixed, and might be known already independent of user preferences. Hence it is useful to
+ * inject that information, using {@link #GenericItemSimilarity(Iterable)}.
+ * </p>
+ *
+ * @param otherSimilarity
+ * other {@link ItemSimilarity} to get similarities from
+ * @param dataModel
+ * data model to get items from
+ * @throws TasteException
+ * if an error occurs while accessing the {@link DataModel} items
*/
public GenericItemSimilarity(ItemSimilarity otherSimilarity, DataModel dataModel) throws TasteException {
long[] itemIDs = IteratorUtils.longIteratorToList(dataModel.getItemIDs());
Iterator<ItemItemSimilarity> it = new DataModelSimilaritiesIterator(otherSimilarity, itemIDs);
initSimilarityMaps(new IteratorIterable<ItemItemSimilarity>(it));
}
-
+
/**
- * <p>Like {@link #GenericItemSimilarity(ItemSimilarity, DataModel)} )}, but will only keep the specified number of
- * similarities from the given {@link DataModel}. It will keep those with the highest similarity -- those that are
- * therefore most important.</p>
- *
- * <p>Thanks to tsmorton for suggesting this and providing part of the implementation.</p>
- *
- * @param otherSimilarity other {@link ItemSimilarity} to get similarities from
- * @param dataModel data model to get items from
- * @param maxToKeep maximum number of similarities to keep
- * @throws TasteException if an error occurs while accessing the {@link DataModel} items
+ * <p>
+ * Like {@link #GenericItemSimilarity(ItemSimilarity, DataModel)} )}, but will only keep the specified
+ * number of similarities from the given {@link DataModel}. It will keep those with the highest similarity
+ * -- those that are therefore most important.
+ * </p>
+ *
+ * <p>
+ * Thanks to tsmorton for suggesting this and providing part of the implementation.
+ * </p>
+ *
+ * @param otherSimilarity
+ * other {@link ItemSimilarity} to get similarities from
+ * @param dataModel
+ * data model to get items from
+ * @param maxToKeep
+ * maximum number of similarities to keep
+ * @throws TasteException
+ * if an error occurs while accessing the {@link DataModel} items
*/
- public GenericItemSimilarity(ItemSimilarity otherSimilarity, DataModel dataModel, int maxToKeep)
- throws TasteException {
+ public GenericItemSimilarity(ItemSimilarity otherSimilarity, DataModel dataModel, int maxToKeep) throws TasteException {
long[] itemIDs = IteratorUtils.longIteratorToList(dataModel.getItemIDs());
Iterator<ItemItemSimilarity> it = new DataModelSimilaritiesIterator(otherSimilarity, itemIDs);
- Iterable<ItemItemSimilarity> keptSimilarities =
- TopItems.getTopItemItemSimilarities(maxToKeep, new IteratorIterable<ItemItemSimilarity>(it));
+ Iterable<ItemItemSimilarity> keptSimilarities = TopItems.getTopItemItemSimilarities(maxToKeep,
+ new IteratorIterable<ItemItemSimilarity>(it));
initSimilarityMaps(keptSimilarities);
}
-
+
private void initSimilarityMaps(Iterable<ItemItemSimilarity> similarities) {
for (ItemItemSimilarity iic : similarities) {
long similarityItemID1 = iic.getItemID1();
@@ -139,14 +169,19 @@
// else similarity between item and itself already assumed to be 1.0
}
}
-
+
/**
- * <p>Returns the similarity between two items. Note that similarity is assumed to be symmetric, that
- * <code>itemSimilarity(item1, item2) == itemSimilarity(item2, item1)</code>, and that <code>itemSimilarity(item1,
- * item1) == 1.0</code> for all items.</p>
- *
- * @param itemID1 first item
- * @param itemID2 second item
+ * <p>
+ * Returns the similarity between two items. Note that similarity is assumed to be symmetric, that
+ * <code>itemSimilarity(item1, item2) == itemSimilarity(item2, item1)</code>, and that
+ * <code>itemSimilarity(item1,
+ * item1) == 1.0</code> for all items.
+ * </p>
+ *
+ * @param itemID1
+ * first item
+ * @param itemID2
+ * second item
* @return similarity between the two
*/
@Override
@@ -170,85 +205,88 @@
Double similarity = nextMap.get(secondID);
return similarity == null ? Double.NaN : similarity;
}
-
+
@Override
public void refresh(Collection<Refreshable> alreadyRefreshed) {
- // Do nothing
+ // Do nothing
}
-
+
/** Encapsulates a similarity between two items. Similarity must be in the range [-1.0,1.0]. */
public static final class ItemItemSimilarity implements Comparable<ItemItemSimilarity> {
-
+
private final long itemID1;
private final long itemID2;
private final double value;
-
+
/**
- * @param itemID1 first item
- * @param itemID2 second item
- * @param value similarity between the two
- * @throws IllegalArgumentException if value is NaN, less than -1.0 or greater than 1.0
+ * @param itemID1
+ * first item
+ * @param itemID2
+ * second item
+ * @param value
+ * similarity between the two
+ * @throws IllegalArgumentException
+ * if value is NaN, less than -1.0 or greater than 1.0
*/
public ItemItemSimilarity(long itemID1, long itemID2, double value) {
- if (Double.isNaN(value) || value < -1.0 || value > 1.0) {
+ if (Double.isNaN(value) || (value < -1.0) || (value > 1.0)) {
throw new IllegalArgumentException("Illegal value: " + value);
}
this.itemID1 = itemID1;
this.itemID2 = itemID2;
this.value = value;
}
-
+
public long getItemID1() {
return itemID1;
}
-
+
public long getItemID2() {
return itemID2;
}
-
+
public double getValue() {
return value;
}
-
+
@Override
public String toString() {
return "ItemItemSimilarity[" + itemID1 + ',' + itemID2 + ':' + value + ']';
}
-
+
/** Defines an ordering from highest similarity to lowest. */
@Override
public int compareTo(ItemItemSimilarity other) {
double otherValue = other.getValue();
return value > otherValue ? -1 : value < otherValue ? 1 : 0;
}
-
+
@Override
public boolean equals(Object other) {
if (!(other instanceof ItemItemSimilarity)) {
return false;
}
ItemItemSimilarity otherSimilarity = (ItemItemSimilarity) other;
- return otherSimilarity.getItemID1() == itemID1 &&
- otherSimilarity.getItemID2() == itemID2 &&
- otherSimilarity.getValue() == value;
+ return (otherSimilarity.getItemID1() == itemID1) && (otherSimilarity.getItemID2() == itemID2)
+ && (otherSimilarity.getValue() == value);
}
-
+
@Override
public int hashCode() {
return (int) itemID1 ^ (int) itemID2 ^ RandomUtils.hashDouble(value);
}
-
+
}
-
+
private static final class DataModelSimilaritiesIterator implements Iterator<ItemItemSimilarity> {
-
+
private final ItemSimilarity otherSimilarity;
private final long[] itemIDs;
private int i;
private long itemID1;
private int j;
private ItemItemSimilarity next;
-
+
private DataModelSimilaritiesIterator(ItemSimilarity otherSimilarity, long[] itemIDs) {
this.otherSimilarity = otherSimilarity;
this.itemIDs = itemIDs;
@@ -257,11 +295,11 @@
j = 1;
goToNext();
}
-
+
private void goToNext() {
next = null;
int size = itemIDs.length;
- while (next == null && i < size - 1) {
+ while ((next == null) && (i < size - 1)) {
long itemID2 = itemIDs[j];
double similarity;
try {
@@ -279,12 +317,12 @@
}
}
}
-
+
@Override
public boolean hasNext() {
return next != null;
}
-
+
@Override
public ItemItemSimilarity next() {
if (next == null) {
@@ -294,12 +332,12 @@
goToNext();
return result;
}
-
+
@Override
public void remove() {
throw new UnsupportedOperationException();
}
-
+
}
-
+
}
Modified: lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/GenericUserSimilarity.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/GenericUserSimilarity.java?rev=909912&r1=909911&r2=909912&view=diff
==============================================================================
--- lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/GenericUserSimilarity.java (original)
+++ lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/GenericUserSimilarity.java Sat Feb 13 20:54:05 2010
@@ -17,49 +17,49 @@
package org.apache.mahout.cf.taste.impl.similarity;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+
import org.apache.mahout.cf.taste.common.Refreshable;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.FastByIDMap;
-import org.apache.mahout.common.iterator.IteratorIterable;
-import org.apache.mahout.common.iterator.IteratorUtils;
-import org.apache.mahout.common.RandomUtils;
import org.apache.mahout.cf.taste.impl.recommender.TopItems;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.similarity.PreferenceInferrer;
import org.apache.mahout.cf.taste.similarity.UserSimilarity;
-
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.NoSuchElementException;
+import org.apache.mahout.common.RandomUtils;
+import org.apache.mahout.common.iterator.IteratorIterable;
+import org.apache.mahout.common.iterator.IteratorUtils;
public final class GenericUserSimilarity implements UserSimilarity {
-
+
private final FastByIDMap<FastByIDMap<Double>> similarityMaps = new FastByIDMap<FastByIDMap<Double>>();
-
+
public GenericUserSimilarity(Iterable<UserUserSimilarity> similarities) {
initSimilarityMaps(similarities);
}
-
+
public GenericUserSimilarity(Iterable<UserUserSimilarity> similarities, int maxToKeep) {
- Iterable<UserUserSimilarity> keptSimilarities = TopItems.getTopUserUserSimilarities(maxToKeep, similarities);
+ Iterable<UserUserSimilarity> keptSimilarities = TopItems.getTopUserUserSimilarities(maxToKeep,
+ similarities);
initSimilarityMaps(keptSimilarities);
}
-
+
public GenericUserSimilarity(UserSimilarity otherSimilarity, DataModel dataModel) throws TasteException {
long[] userIDs = IteratorUtils.longIteratorToList(dataModel.getUserIDs());
Iterator<UserUserSimilarity> it = new DataModelSimilaritiesIterator(otherSimilarity, userIDs);
initSimilarityMaps(new IteratorIterable<UserUserSimilarity>(it));
}
-
- public GenericUserSimilarity(UserSimilarity otherSimilarity, DataModel dataModel, int maxToKeep)
- throws TasteException {
+
+ public GenericUserSimilarity(UserSimilarity otherSimilarity, DataModel dataModel, int maxToKeep) throws TasteException {
long[] userIDs = IteratorUtils.longIteratorToList(dataModel.getUserIDs());
Iterator<UserUserSimilarity> it = new DataModelSimilaritiesIterator(otherSimilarity, userIDs);
- Iterable<UserUserSimilarity> keptSimilarities =
- TopItems.getTopUserUserSimilarities(maxToKeep, new IteratorIterable<UserUserSimilarity>(it));
+ Iterable<UserUserSimilarity> keptSimilarities = TopItems.getTopUserUserSimilarities(maxToKeep,
+ new IteratorIterable<UserUserSimilarity>(it));
initSimilarityMaps(keptSimilarities);
}
-
+
private void initSimilarityMaps(Iterable<UserUserSimilarity> similarities) {
for (UserUserSimilarity uuc : similarities) {
long similarityUser1 = uuc.getUserID1();
@@ -85,7 +85,7 @@
// else similarity between user and itself already assumed to be 1.0
}
}
-
+
@Override
public double userSimilarity(long userID1, long userID2) {
if (userID1 == userID2) {
@@ -107,83 +107,82 @@
Double similarity = nextMap.get(second);
return similarity == null ? Double.NaN : similarity;
}
-
+
@Override
public void setPreferenceInferrer(PreferenceInferrer inferrer) {
throw new UnsupportedOperationException();
}
-
+
@Override
public void refresh(Collection<Refreshable> alreadyRefreshed) {
- // Do nothing
+ // Do nothing
}
-
+
public static final class UserUserSimilarity implements Comparable<UserUserSimilarity> {
-
+
private final long userID1;
private final long userID2;
private final double value;
-
+
public UserUserSimilarity(long userID1, long userID2, double value) {
- if (Double.isNaN(value) || value < -1.0 || value > 1.0) {
+ if (Double.isNaN(value) || (value < -1.0) || (value > 1.0)) {
throw new IllegalArgumentException("Illegal value: " + value);
}
this.userID1 = userID1;
this.userID2 = userID2;
this.value = value;
}
-
+
public long getUserID1() {
return userID1;
}
-
+
public long getUserID2() {
return userID2;
}
-
+
public double getValue() {
return value;
}
-
+
@Override
public String toString() {
return "UserUserSimilarity[" + userID1 + ',' + userID2 + ':' + value + ']';
}
-
+
/** Defines an ordering from highest similarity to lowest. */
@Override
public int compareTo(UserUserSimilarity other) {
double otherValue = other.getValue();
return value > otherValue ? -1 : value < otherValue ? 1 : 0;
}
-
+
@Override
public boolean equals(Object other) {
if (!(other instanceof UserUserSimilarity)) {
return false;
}
UserUserSimilarity otherSimilarity = (UserUserSimilarity) other;
- return otherSimilarity.getUserID1() == userID1 &&
- otherSimilarity.getUserID2() == userID2 &&
- otherSimilarity.getValue() == value;
+ return (otherSimilarity.getUserID1() == userID1) && (otherSimilarity.getUserID2() == userID2)
+ && (otherSimilarity.getValue() == value);
}
-
+
@Override
public int hashCode() {
return (int) userID1 ^ (int) userID2 ^ RandomUtils.hashDouble(value);
}
-
+
}
-
+
private static final class DataModelSimilaritiesIterator implements Iterator<UserUserSimilarity> {
-
+
private final UserSimilarity otherSimilarity;
private final long[] userIDs;
private final int size;
private int i;
private long userID1;
private int j;
-
+
private DataModelSimilaritiesIterator(UserSimilarity otherSimilarity, long[] userIDs) {
this.otherSimilarity = otherSimilarity;
this.userIDs = userIDs;
@@ -192,12 +191,12 @@
userID1 = userIDs[0];
j = 1;
}
-
+
@Override
public boolean hasNext() {
return i < size - 1;
}
-
+
@Override
public UserUserSimilarity next() {
if (!hasNext()) {
@@ -220,12 +219,12 @@
}
return result;
}
-
+
@Override
public void remove() {
throw new UnsupportedOperationException();
}
-
+
}
-
+
}
\ No newline at end of file
Modified: lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/LogLikelihoodSimilarity.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/LogLikelihoodSimilarity.java?rev=909912&r1=909911&r2=909912&view=diff
==============================================================================
--- lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/LogLikelihoodSimilarity.java (original)
+++ lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/LogLikelihoodSimilarity.java Sat Feb 13 20:54:05 2010
@@ -17,6 +17,8 @@
package org.apache.mahout.cf.taste.impl.similarity;
+import java.util.Collection;
+
import org.apache.mahout.cf.taste.common.Refreshable;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.FastIDSet;
@@ -26,17 +28,15 @@
import org.apache.mahout.cf.taste.similarity.PreferenceInferrer;
import org.apache.mahout.cf.taste.similarity.UserSimilarity;
-import java.util.Collection;
-
/** See <a href="http://citeseer.ist.psu.edu/29096.html">http://citeseer.ist.psu.edu/29096.html</a>. */
public final class LogLikelihoodSimilarity implements UserSimilarity, ItemSimilarity {
-
+
private final DataModel dataModel;
-
+
public LogLikelihoodSimilarity(DataModel dataModel) {
this.dataModel = dataModel;
}
-
+
/**
* @throws UnsupportedOperationException
*/
@@ -44,29 +44,27 @@
public void setPreferenceInferrer(PreferenceInferrer inferrer) {
throw new UnsupportedOperationException();
}
-
+
@Override
public double userSimilarity(long userID1, long userID2) throws TasteException {
-
+
FastIDSet prefs1 = dataModel.getItemIDsFromUser(userID1);
FastIDSet prefs2 = dataModel.getItemIDsFromUser(userID2);
-
+
int prefs1Size = prefs1.size();
int prefs2Size = prefs2.size();
- int intersectionSize = prefs1Size < prefs2Size ?
- prefs2.intersectionSize(prefs1) :
- prefs1.intersectionSize(prefs2);
+ int intersectionSize = prefs1Size < prefs2Size ? prefs2.intersectionSize(prefs1) : prefs1
+ .intersectionSize(prefs2);
if (intersectionSize == 0) {
return Double.NaN;
}
int numItems = dataModel.getNumItems();
- double logLikelihood = twoLogLambda(intersectionSize,
- prefs1Size - intersectionSize,
- prefs2Size,
- numItems - prefs2Size);
+ double logLikelihood = LogLikelihoodSimilarity.twoLogLambda(intersectionSize, prefs1Size
+ - intersectionSize,
+ prefs2Size, numItems - prefs2Size);
return 1.0 - 1.0 / (1.0 + logLikelihood);
}
-
+
@Override
public double itemSimilarity(long itemID1, long itemID2) throws TasteException {
int preferring1and2 = dataModel.getNumUsersWithPreferenceFor(itemID1, itemID2);
@@ -76,33 +74,36 @@
int preferring1 = dataModel.getNumUsersWithPreferenceFor(itemID1);
int preferring2 = dataModel.getNumUsersWithPreferenceFor(itemID2);
int numUsers = dataModel.getNumUsers();
- double logLikelihood =
- twoLogLambda(preferring1and2, preferring1 - preferring1and2, preferring2, numUsers - preferring2);
+ double logLikelihood = LogLikelihoodSimilarity.twoLogLambda(preferring1and2, preferring1
+ - preferring1and2,
+ preferring2, numUsers - preferring2);
return 1.0 - 1.0 / (1.0 + logLikelihood);
}
-
+
static double twoLogLambda(double k1, double k2, double n1, double n2) {
double p = (k1 + k2) / (n1 + n2);
- return 2.0 * (logL(k1 / n1, k1, n1) + logL(k2 / n2, k2, n2) - logL(p, k1, n1) - logL(p, k2, n2));
+ return 2.0 * (LogLikelihoodSimilarity.logL(k1 / n1, k1, n1)
+ + LogLikelihoodSimilarity.logL(k2 / n2, k2, n2) - LogLikelihoodSimilarity.logL(p, k1, n1) - LogLikelihoodSimilarity
+ .logL(p, k2, n2));
}
-
+
private static double logL(double p, double k, double n) {
- return k * safeLog(p) + (n - k) * safeLog(1.0 - p);
+ return k * LogLikelihoodSimilarity.safeLog(p) + (n - k) * LogLikelihoodSimilarity.safeLog(1.0 - p);
}
-
+
private static double safeLog(double d) {
return d <= 0.0 ? 0.0 : Math.log(d);
}
-
+
@Override
public void refresh(Collection<Refreshable> alreadyRefreshed) {
alreadyRefreshed = RefreshHelper.buildRefreshed(alreadyRefreshed);
RefreshHelper.maybeRefresh(alreadyRefreshed, dataModel);
}
-
+
@Override
public String toString() {
return "LogLikelihoodSimilarity[dataModel:" + dataModel + ']';
}
-
+
}
\ No newline at end of file
Modified: lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/PearsonCorrelationSimilarity.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/PearsonCorrelationSimilarity.java?rev=909912&r1=909911&r2=909912&view=diff
==============================================================================
--- lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/PearsonCorrelationSimilarity.java (original)
+++ lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/PearsonCorrelationSimilarity.java Sat Feb 13 20:54:05 2010
@@ -22,33 +22,45 @@
import org.apache.mahout.cf.taste.model.DataModel;
/**
- * <p>An implementation of the Pearson correlation. For users X and Y, the following values are calculated:</p>
- *
- * <ul> <li>sumX2: sum of the square of all X's preference values</li> <li>sumY2: sum of the square of all Y's
- * preference values</li> <li>sumXY: sum of the product of X and Y's preference value for all items for which both X and
- * Y express a preference</li> </ul>
- *
- * <p>The correlation is then:
- *
- * <p><code>sumXY / sqrt(sumX2 * sumY2)</code></p>
- *
- * <p>Note that this correlation "centers" its data, shifts the user's preference values so that each of their means is
- * 0. This is necessary to achieve expected behavior on all data sets.</p>
- *
- * <p>This correlation implementation is equivalent to the cosine measure correlation since the data it receives is
- * assumed to be centered -- mean is 0. The correlation may be interpreted as the cosine of the angle between the two
- * vectors defined by the users' preference values.</p>
+ * <p>
+ * An implementation of the Pearson correlation. For users X and Y, the following values are calculated:
+ * </p>
+ *
+ * <ul>
+ * <li>sumX2: sum of the square of all X's preference values</li>
+ * <li>sumY2: sum of the square of all Y's preference values</li>
+ * <li>sumXY: sum of the product of X and Y's preference value for all items for which both X and Y express a
+ * preference</li>
+ * </ul>
+ *
+ * <p>
+ * The correlation is then:
+ *
+ * <p>
+ * <code>sumXY / sqrt(sumX2 * sumY2)</code>
+ * </p>
+ *
+ * <p>
+ * Note that this correlation "centers" its data, shifts the user's preference values so that each of their
+ * means is 0. This is necessary to achieve expected behavior on all data sets.
+ * </p>
+ *
+ * <p>
+ * This correlation implementation is equivalent to the cosine measure correlation since the data it receives
+ * is assumed to be centered -- mean is 0. The correlation may be interpreted as the cosine of the angle
+ * between the two vectors defined by the users' preference values.
+ * </p>
*/
public final class PearsonCorrelationSimilarity extends AbstractSimilarity {
-
+
public PearsonCorrelationSimilarity(DataModel dataModel) throws TasteException {
super(dataModel);
}
-
+
public PearsonCorrelationSimilarity(DataModel dataModel, Weighting weighting) throws TasteException {
super(dataModel, weighting);
}
-
+
@Override
double computeResult(int n, double sumXY, double sumX2, double sumY2, double sumXYdiff2) {
if (n == 0) {
@@ -66,5 +78,5 @@
}
return sumXY / denominator;
}
-
+
}
Modified: lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/SpearmanCorrelationSimilarity.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/SpearmanCorrelationSimilarity.java?rev=909912&r1=909911&r2=909912&view=diff
==============================================================================
--- lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/SpearmanCorrelationSimilarity.java (original)
+++ lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/SpearmanCorrelationSimilarity.java Sat Feb 13 20:54:05 2010
@@ -17,6 +17,8 @@
package org.apache.mahout.cf.taste.impl.similarity;
+import java.util.Collection;
+
import org.apache.mahout.cf.taste.common.Refreshable;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.RefreshHelper;
@@ -25,43 +27,43 @@
import org.apache.mahout.cf.taste.similarity.PreferenceInferrer;
import org.apache.mahout.cf.taste.similarity.UserSimilarity;
-import java.util.Collection;
-
/**
- * <p>Like {@link PearsonCorrelationSimilarity}, but compares relative ranking of preference values instead of
+ * <p>
+ * Like {@link PearsonCorrelationSimilarity}, but compares relative ranking of preference values instead of
* preference values themselves. That is, each user's preferences are sorted and then assign a rank as their
- * preference value, with 1 being assigned to the least preferred item.</p>
+ * preference value, with 1 being assigned to the least preferred item.
+ * </p>
*/
public final class SpearmanCorrelationSimilarity implements UserSimilarity {
-
+
private final DataModel dataModel;
-
+
public SpearmanCorrelationSimilarity(DataModel dataModel) {
if (dataModel == null) {
throw new IllegalArgumentException("dataModel is null");
}
this.dataModel = dataModel;
}
-
+
@Override
public double userSimilarity(long userID1, long userID2) throws TasteException {
PreferenceArray xPrefs = dataModel.getPreferencesFromUser(userID1);
PreferenceArray yPrefs = dataModel.getPreferencesFromUser(userID2);
int xLength = xPrefs.length();
int yLength = yPrefs.length();
-
- if (xLength <= 1 || yLength <= 1) {
+
+ if ((xLength <= 1) || (yLength <= 1)) {
return Double.NaN;
}
-
+
// Copy prefs since we need to modify pref values to ranks
xPrefs = xPrefs.clone();
yPrefs = yPrefs.clone();
-
+
// First sort by values from low to high
xPrefs.sortByValue();
yPrefs.sortByValue();
-
+
// Assign ranks from low to high
float nextRank = 1.0f;
for (int i = 0; i < xLength; i++) {
@@ -79,18 +81,18 @@
nextRank += 1.0f;
}
}
-
+
xPrefs.sortByItem();
yPrefs.sortByItem();
-
+
long xIndex = xPrefs.getItemID(0);
long yIndex = yPrefs.getItemID(0);
int xPrefIndex = 0;
int yPrefIndex = 0;
-
+
double sumXYRankDiff2 = 0.0;
int count = 0;
-
+
while (true) {
int compare = xIndex < yIndex ? -1 : xIndex > yIndex ? 1 : 0;
if (compare == 0) {
@@ -111,24 +113,24 @@
yIndex = yPrefs.getItemID(yPrefIndex);
}
}
-
+
if (count <= 1) {
return Double.NaN;
}
-
+
// When ranks are unique, this formula actually gives the Pearson correlation
- return 1.0 - (6.0 * sumXYRankDiff2 / (count * (count*count - 1)));
+ return 1.0 - 6.0 * sumXYRankDiff2 / (count * (count * count - 1));
}
-
+
@Override
public void setPreferenceInferrer(PreferenceInferrer inferrer) {
throw new UnsupportedOperationException();
}
-
+
@Override
public void refresh(Collection<Refreshable> alreadyRefreshed) {
alreadyRefreshed = RefreshHelper.buildRefreshed(alreadyRefreshed);
RefreshHelper.maybeRefresh(alreadyRefreshed, dataModel);
}
-
+
}
Modified: lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/TanimotoCoefficientSimilarity.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/TanimotoCoefficientSimilarity.java?rev=909912&r1=909911&r2=909912&view=diff
==============================================================================
--- lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/TanimotoCoefficientSimilarity.java (original)
+++ lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/TanimotoCoefficientSimilarity.java Sat Feb 13 20:54:05 2010
@@ -17,6 +17,8 @@
package org.apache.mahout.cf.taste.impl.similarity;
+import java.util.Collection;
+
import org.apache.mahout.cf.taste.common.Refreshable;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.FastIDSet;
@@ -26,27 +28,31 @@
import org.apache.mahout.cf.taste.similarity.PreferenceInferrer;
import org.apache.mahout.cf.taste.similarity.UserSimilarity;
-import java.util.Collection;
-
/**
- * <p>An implementation of a "similarity" based on the
- * <a href="http://en.wikipedia.org/wiki/Jaccard_index#Tanimoto_coefficient_.28extended_Jaccard_coefficient.29">
+ * <p>
+ * An implementation of a "similarity" based on the <a
+ * href="http://en.wikipedia.org/wiki/Jaccard_index#Tanimoto_coefficient_.28extended_Jaccard_coefficient.29">
* Tanimoto coefficient</a>, or extended <a href="http://en.wikipedia.org/wiki/Jaccard_index">Jaccard
- * coefficient</a>.</p>
- *
- * <p>This is intended for "binary" data sets where a user either expresses a generic "yes" preference for an item or
- * has no preference. The actual preference values do not matter here, only their presence or absence.</p>
- *
- * <p>The value returned is in [0,1].</p>
+ * coefficient</a>.
+ * </p>
+ *
+ * <p>
+ * This is intended for "binary" data sets where a user either expresses a generic "yes" preference for an
+ * item or has no preference. The actual preference values do not matter here, only their presence or absence.
+ * </p>
+ *
+ * <p>
+ * The value returned is in [0,1].
+ * </p>
*/
public final class TanimotoCoefficientSimilarity implements UserSimilarity, ItemSimilarity {
-
+
private final DataModel dataModel;
-
+
public TanimotoCoefficientSimilarity(DataModel dataModel) {
this.dataModel = dataModel;
}
-
+
/**
* @throws UnsupportedOperationException
*/
@@ -54,30 +60,30 @@
public void setPreferenceInferrer(PreferenceInferrer inferrer) {
throw new UnsupportedOperationException();
}
-
+
@Override
public double userSimilarity(long userID1, long userID2) throws TasteException {
-
+
FastIDSet xPrefs = dataModel.getItemIDsFromUser(userID1);
FastIDSet yPrefs = dataModel.getItemIDsFromUser(userID2);
-
+
if (xPrefs.isEmpty() && yPrefs.isEmpty()) {
return Double.NaN;
}
if (xPrefs.isEmpty() || yPrefs.isEmpty()) {
return 0.0;
}
-
+
int intersectionSize = xPrefs.intersectionSize(yPrefs);
if (intersectionSize == 0) {
return Double.NaN;
}
-
+
int unionSize = xPrefs.size() + yPrefs.size() - intersectionSize;
-
+
return (double) intersectionSize / (double) unionSize;
}
-
+
@Override
public double itemSimilarity(long itemID1, long itemID2) throws TasteException {
int preferring1and2 = dataModel.getNumUsersWithPreferenceFor(itemID1, itemID2);
@@ -85,16 +91,16 @@
int preferring2 = dataModel.getNumUsersWithPreferenceFor(itemID2);
return (double) preferring1and2 / (double) (preferring1 + preferring2 - preferring1and2);
}
-
+
@Override
public void refresh(Collection<Refreshable> alreadyRefreshed) {
alreadyRefreshed = RefreshHelper.buildRefreshed(alreadyRefreshed);
RefreshHelper.maybeRefresh(alreadyRefreshed, dataModel);
}
-
+
@Override
public String toString() {
return "TanimotoCoefficientSimilarity[dataModel:" + dataModel + ']';
}
-
+
}
\ No newline at end of file
Modified: lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/jdbc/AbstractJDBCItemSimilarity.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/jdbc/AbstractJDBCItemSimilarity.java?rev=909912&r1=909911&r2=909912&view=diff
==============================================================================
--- lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/jdbc/AbstractJDBCItemSimilarity.java (original)
+++ lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/jdbc/AbstractJDBCItemSimilarity.java Sat Feb 13 20:54:05 2010
@@ -17,71 +17,69 @@
package org.apache.mahout.cf.taste.impl.similarity.jdbc;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Collection;
+
+import javax.sql.DataSource;
+
import org.apache.mahout.cf.taste.common.NoSuchItemException;
import org.apache.mahout.cf.taste.common.Refreshable;
import org.apache.mahout.cf.taste.common.TasteException;
-import org.apache.mahout.common.IOUtils;
import org.apache.mahout.cf.taste.impl.common.jdbc.AbstractJDBCComponent;
import org.apache.mahout.cf.taste.impl.model.jdbc.ConnectionPoolDataSource;
import org.apache.mahout.cf.taste.similarity.ItemSimilarity;
+import org.apache.mahout.common.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import javax.sql.DataSource;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.Collection;
-
/**
- * An {@link ItemSimilarity} which draws pre-computed item-item similarities from
- * a database table via JDBC.
+ * An {@link ItemSimilarity} which draws pre-computed item-item similarities from a database table via JDBC.
*/
public abstract class AbstractJDBCItemSimilarity extends AbstractJDBCComponent implements ItemSimilarity {
-
+
private static final Logger log = LoggerFactory.getLogger(AbstractJDBCItemSimilarity.class);
-
+
static final String DEFAULT_SIMILARITY_TABLE = "taste_item_similarity";
static final String DEFAULT_ITEM_A_ID_COLUMN = "item_id_a";
static final String DEFAULT_ITEM_B_ID_COLUMN = "item_id_b";
static final String DEFAULT_SIMILARITY_COLUMN = "similarity";
-
+
private final DataSource dataSource;
private final String similarityTable;
private final String itemAIDColumn;
private final String itemBIDColumn;
private final String similarityColumn;
private final String getItemItemSimilaritySQL;
-
- protected AbstractJDBCItemSimilarity(DataSource dataSource,
- String getItemItemSimilaritySQL) {
- this(dataSource,
- DEFAULT_SIMILARITY_TABLE,
- DEFAULT_ITEM_A_ID_COLUMN,
- DEFAULT_ITEM_B_ID_COLUMN,
- DEFAULT_SIMILARITY_COLUMN,
- getItemItemSimilaritySQL);
+
+ protected AbstractJDBCItemSimilarity(DataSource dataSource, String getItemItemSimilaritySQL) {
+ this(dataSource, AbstractJDBCItemSimilarity.DEFAULT_SIMILARITY_TABLE,
+ AbstractJDBCItemSimilarity.DEFAULT_ITEM_A_ID_COLUMN,
+ AbstractJDBCItemSimilarity.DEFAULT_ITEM_B_ID_COLUMN,
+ AbstractJDBCItemSimilarity.DEFAULT_SIMILARITY_COLUMN, getItemItemSimilaritySQL);
}
-
+
protected AbstractJDBCItemSimilarity(DataSource dataSource,
String similarityTable,
String itemAIDColumn,
String itemBIDColumn,
String similarityColumn,
String getItemItemSimilaritySQL) {
- checkNotNullAndLog("similarityTable", similarityTable);
- checkNotNullAndLog("itemAIDColumn", itemAIDColumn);
- checkNotNullAndLog("itemBIDColumn", itemBIDColumn);
- checkNotNullAndLog("similarityColumn", similarityColumn);
-
- checkNotNullAndLog("getItemItemSimilaritySQL", getItemItemSimilaritySQL);
-
+ AbstractJDBCComponent.checkNotNullAndLog("similarityTable", similarityTable);
+ AbstractJDBCComponent.checkNotNullAndLog("itemAIDColumn", itemAIDColumn);
+ AbstractJDBCComponent.checkNotNullAndLog("itemBIDColumn", itemBIDColumn);
+ AbstractJDBCComponent.checkNotNullAndLog("similarityColumn", similarityColumn);
+
+ AbstractJDBCComponent.checkNotNullAndLog("getItemItemSimilaritySQL", getItemItemSimilaritySQL);
+
if (!(dataSource instanceof ConnectionPoolDataSource)) {
- log.warn("You are not using ConnectionPoolDataSource. Make sure your DataSource pools connections " +
- "to the database itself, or database performance will be severely reduced.");
+ AbstractJDBCItemSimilarity.log
+ .warn("You are not using ConnectionPoolDataSource. Make sure your DataSource pools connections "
+ + "to the database itself, or database performance will be severely reduced.");
}
-
+
this.dataSource = dataSource;
this.similarityTable = similarityTable;
this.itemAIDColumn = itemAIDColumn;
@@ -89,26 +87,26 @@
this.similarityColumn = similarityColumn;
this.getItemItemSimilaritySQL = getItemItemSimilaritySQL;
}
-
+
protected String getSimilarityTable() {
return similarityTable;
}
-
+
protected String getItemAIDColumn() {
return itemAIDColumn;
}
-
+
protected String getItemBIDColumn() {
return itemBIDColumn;
}
-
+
protected String getSimilarityColumn() {
return similarityColumn;
}
-
+
@Override
public double itemSimilarity(long itemID1, long itemID2) throws TasteException {
-
+
if (itemID1 == itemID2) {
return 1.0;
}
@@ -118,39 +116,40 @@
itemID1 = itemID2;
itemID2 = temp;
}
-
+
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
-
+
try {
conn = dataSource.getConnection();
- stmt = conn.prepareStatement(getItemItemSimilaritySQL, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
+ stmt = conn.prepareStatement(getItemItemSimilaritySQL, ResultSet.TYPE_FORWARD_ONLY,
+ ResultSet.CONCUR_READ_ONLY);
stmt.setFetchDirection(ResultSet.FETCH_FORWARD);
stmt.setFetchSize(getFetchSize());
stmt.setLong(1, itemID1);
stmt.setLong(2, itemID2);
-
- log.debug("Executing SQL query: {}", getItemItemSimilaritySQL);
+
+ AbstractJDBCItemSimilarity.log.debug("Executing SQL query: {}", getItemItemSimilaritySQL);
rs = stmt.executeQuery();
-
+
if (rs.next()) {
return rs.getDouble(1);
} else {
throw new NoSuchItemException();
}
-
+
} catch (SQLException sqle) {
- log.warn("Exception while retrieving user", sqle);
+ AbstractJDBCItemSimilarity.log.warn("Exception while retrieving user", sqle);
throw new TasteException(sqle);
} finally {
IOUtils.quietClose(rs, stmt, conn);
}
}
-
+
@Override
public void refresh(Collection<Refreshable> alreadyRefreshed) {
- // do nothing
+ // do nothing
}
-
+
}
Modified: lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/jdbc/MySQLJDBCItemSimilarity.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/jdbc/MySQLJDBCItemSimilarity.java?rev=909912&r1=909911&r2=909912&view=diff
==============================================================================
--- lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/jdbc/MySQLJDBCItemSimilarity.java (original)
+++ lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/jdbc/MySQLJDBCItemSimilarity.java Sat Feb 13 20:54:05 2010
@@ -17,77 +17,99 @@
package org.apache.mahout.cf.taste.impl.similarity.jdbc;
+import javax.sql.DataSource;
+
import org.apache.mahout.cf.taste.common.TasteException;
+import org.apache.mahout.cf.taste.impl.common.jdbc.AbstractJDBCComponent;
import org.apache.mahout.cf.taste.similarity.ItemSimilarity;
-import javax.sql.DataSource;
-
/**
- * <p>An {@link ItemSimilarity} backed by a MySQL database and accessed via JDBC.
- * It may work with other JDBC databases. By default, this class assumes that there is a {@link DataSource}
- * available under the JNDI name "jdbc/taste", which
- * gives access to a database with a "taste_item_similarity" table with the following schema:</p>
- *
+ * <p>
+ * An {@link ItemSimilarity} backed by a MySQL database and accessed via JDBC. It may work with other JDBC
+ * databases. By default, this class assumes that there is a {@link DataSource} available under the JNDI name
+ * "jdbc/taste", which gives access to a database with a "taste_item_similarity" table with the following
+ * schema:
+ * </p>
+ *
* <table>
- * <tr><th>item_id_a</th><th>item_id_b</th><th>similarity</th></tr>
- * <tr><td>ABC</td><td>DEF</td><td>0.9</td></tr>
- * <tr><td>DEF</td><td>EFG</td><td>0.1</td></tr>
+ * <tr>
+ * <th>item_id_a</th>
+ * <th>item_id_b</th>
+ * <th>similarity</th>
+ * </tr>
+ * <tr>
+ * <td>ABC</td>
+ * <td>DEF</td>
+ * <td>0.9</td>
+ * </tr>
+ * <tr>
+ * <td>DEF</td>
+ * <td>EFG</td>
+ * <td>0.1</td>
+ * </tr>
* </table>
- *
- * <p>For example, the following command sets up a suitable table in MySQL,
- * complete with primary key and indexes:</p>
- *
- * <p><pre>
+ *
+ * <p>
+ * For example, the following command sets up a suitable table in MySQL, complete with primary key and
+ * indexes:
+ * </p>
+ *
+ * <p>
+ *
+ * <pre>
* CREATE TABLE taste_item_similarity (
* item_id_a BIGINT NOT NULL,
* item_id_b BIGINT NOT NULL,
* similarity FLOAT NOT NULL,
* PRIMARY KEY (item_id_a, item_id_b),
* )
- * </pre></p>
- *
- * <p>Note that for each row, item_id_a should be "less than" item_id_b. It is redundant to store it
- * both ways, so the pair is always stored as a pair with the lesser one first.
- *
+ * </pre>
+ *
+ * </p>
+ *
+ * <p>
+ * Note that for each row, item_id_a should be "less than" item_id_b. It is redundant to store it both ways,
+ * so the pair is always stored as a pair with the lesser one first.
+ *
* @see org.apache.mahout.cf.taste.impl.recommender.slopeone.jdbc.MySQLJDBCDiffStorage
* @see org.apache.mahout.cf.taste.impl.model.jdbc.MySQLJDBCDataModel
*/
public final class MySQLJDBCItemSimilarity extends AbstractJDBCItemSimilarity {
-
+
public MySQLJDBCItemSimilarity() throws TasteException {
- this(DEFAULT_DATASOURCE_NAME);
+ this(AbstractJDBCComponent.DEFAULT_DATASOURCE_NAME);
}
-
+
public MySQLJDBCItemSimilarity(String dataSourceName) throws TasteException {
- this(lookupDataSource(dataSourceName));
+ this(AbstractJDBCComponent.lookupDataSource(dataSourceName));
}
-
+
public MySQLJDBCItemSimilarity(DataSource dataSource) {
- this(dataSource,
- DEFAULT_SIMILARITY_TABLE,
- DEFAULT_ITEM_A_ID_COLUMN,
- DEFAULT_ITEM_B_ID_COLUMN,
- DEFAULT_SIMILARITY_COLUMN);
+ this(dataSource, AbstractJDBCItemSimilarity.DEFAULT_SIMILARITY_TABLE,
+ AbstractJDBCItemSimilarity.DEFAULT_ITEM_A_ID_COLUMN,
+ AbstractJDBCItemSimilarity.DEFAULT_ITEM_B_ID_COLUMN,
+ AbstractJDBCItemSimilarity.DEFAULT_SIMILARITY_COLUMN);
}
-
+
public MySQLJDBCItemSimilarity(DataSource dataSource,
String similarityTable,
String itemAIDColumn,
String itemBIDColumn,
String similarityColumn) {
- super(dataSource,
- similarityTable,
- itemAIDColumn,
- itemBIDColumn,
- similarityColumn,
- "SELECT " + similarityColumn + " FROM " + similarityTable + " WHERE " + itemAIDColumn + "=? AND " +
- itemBIDColumn + "=?");
+ super(dataSource, similarityTable, itemAIDColumn, itemBIDColumn, similarityColumn, "SELECT "
+ + similarityColumn
+ + " FROM "
+ + similarityTable
+ + " WHERE "
+ + itemAIDColumn
+ + "=? AND "
+ + itemBIDColumn + "=?");
}
-
+
@Override
protected int getFetchSize() {
// Need to return this for MySQL Connector/J to make it use streaming mode
return Integer.MIN_VALUE;
}
-
+
}
\ No newline at end of file
Modified: lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/CaseAmplification.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/CaseAmplification.java?rev=909912&r1=909911&r2=909912&view=diff
==============================================================================
--- lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/CaseAmplification.java (original)
+++ lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/CaseAmplification.java Sat Feb 13 20:54:05 2010
@@ -17,55 +17,66 @@
package org.apache.mahout.cf.taste.impl.transforms;
+import java.util.Collection;
+
import org.apache.mahout.cf.taste.common.Refreshable;
import org.apache.mahout.cf.taste.transforms.SimilarityTransform;
-import java.util.Collection;
-
/**
- * <p>Applies "case amplification" to similarities. This essentially makes big values bigger and small values smaller by
- * raising each score to a power. It could however be used to achieve the opposite effect.</p>
+ * <p>
+ * Applies "case amplification" to similarities. This essentially makes big values bigger and small values
+ * smaller by raising each score to a power. It could however be used to achieve the opposite effect.
+ * </p>
*/
public final class CaseAmplification implements SimilarityTransform {
-
+
private final double factor;
-
+
/**
- * <p>Creates a {@link CaseAmplification} transformation based on the given factor.</p>
- *
- * @param factor transformation factor
- * @throws IllegalArgumentException if factor is 0.0 or {@link Double#NaN}
+ * <p>
+ * Creates a {@link CaseAmplification} transformation based on the given factor.
+ * </p>
+ *
+ * @param factor
+ * transformation factor
+ * @throws IllegalArgumentException
+ * if factor is 0.0 or {@link Double#NaN}
*/
public CaseAmplification(double factor) {
- if (Double.isNaN(factor) || factor == 0.0) {
+ if (Double.isNaN(factor) || (factor == 0.0)) {
throw new IllegalArgumentException("factor is 0 or NaN");
}
this.factor = factor;
}
-
+
/**
- * <p>Transforms one similarity value. This implementation is such that it's possible to define this transformation on
- * one value in isolation. The "thing" parameters are therefore unused.</p>
- *
- * @param id1 unused
- * @param id2 unused
- * @param value similarity to transform
- * @return <code>value<sup>factor</sup></code> if value is nonnegative; <code>-value<sup>-factor</sup></code>
- * otherwise
+ * <p>
+ * Transforms one similarity value. This implementation is such that it's possible to define this
+ * transformation on one value in isolation. The "thing" parameters are therefore unused.
+ * </p>
+ *
+ * @param id1
+ * unused
+ * @param id2
+ * unused
+ * @param value
+ * similarity to transform
+ * @return <code>value<sup>factor</sup></code> if value is nonnegative;
+ * <code>-value<sup>-factor</sup></code> otherwise
*/
@Override
public double transformSimilarity(long id1, long id2, double value) {
return value < 0.0 ? -Math.pow(-value, factor) : Math.pow(value, factor);
}
-
+
@Override
public void refresh(Collection<Refreshable> alreadyRefreshed) {
- // do nothing
+ // do nothing
}
-
+
@Override
public String toString() {
return "CaseAmplification[factor:" + factor + ']';
}
-
+
}
Modified: lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/Counters.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/Counters.java?rev=909912&r1=909911&r2=909912&view=diff
==============================================================================
--- lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/Counters.java (original)
+++ lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/Counters.java Sat Feb 13 20:54:05 2010
@@ -17,15 +17,19 @@
package org.apache.mahout.cf.taste.impl.transforms;
-import org.apache.mahout.cf.taste.impl.common.FastByIDMap;
-
import java.util.Map;
-/** <p>A simple, fast utility class that maps keys to counts.</p> */
-final class Counters {
+import org.apache.mahout.cf.taste.impl.common.FastByIDMap;
+/**
+ * <p>
+ * A simple, fast utility class that maps keys to counts.
+ * </p>
+ */
+final class Counters {
+
private final FastByIDMap<int[]> counts = new FastByIDMap<int[]>();
-
+
void increment(long key) {
int[] count = counts.get(key);
if (count == null) {
@@ -36,23 +40,23 @@
count[0]++;
}
}
-
+
int getCount(long key) {
int[] count = counts.get(key);
return count == null ? 0 : count[0];
}
-
+
int size() {
return counts.size();
}
-
- Iterable<Map.Entry<Long, int[]>> getEntrySet() {
+
+ Iterable<Map.Entry<Long,int[]>> getEntrySet() {
return counts.entrySet();
}
-
+
@Override
public String toString() {
return "Counters[" + counts + ']';
}
-
+
}
Modified: lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/InverseUserFrequency.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/InverseUserFrequency.java?rev=909912&r1=909911&r2=909912&view=diff
==============================================================================
--- lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/InverseUserFrequency.java (original)
+++ lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/InverseUserFrequency.java Sat Feb 13 20:54:05 2010
@@ -17,6 +17,11 @@
package org.apache.mahout.cf.taste.impl.transforms;
+import java.util.Collection;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.atomic.AtomicReference;
+
import org.apache.mahout.cf.taste.common.Refreshable;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.FastByIDMap;
@@ -27,44 +32,48 @@
import org.apache.mahout.cf.taste.model.PreferenceArray;
import org.apache.mahout.cf.taste.transforms.PreferenceTransform;
-import java.util.Collection;
-import java.util.Map;
-import java.util.concurrent.Callable;
-import java.util.concurrent.atomic.AtomicReference;
-
/**
- * <p>Implements an "inverse user frequency" transformation, which boosts preference values for items for which few
- * users have expressed a preference, and reduces preference values for items for which many users have expressed a
- * preference. The idea is that these "rare" items are more useful in deciding how similar two users' tastes
- * are, and so should be emphasized in other calculatioons. This idea is mentioned in <a
+ * <p>
+ * Implements an "inverse user frequency" transformation, which boosts preference values for items for which
+ * few users have expressed a preference, and reduces preference values for items for which many users have
+ * expressed a preference. The idea is that these "rare" items are more useful in deciding how similar two
+ * users' tastes are, and so should be emphasized in other calculatioons. This idea is mentioned in <a
* href="ftp://ftp.research.microsoft.com/pub/tr/tr-98-12.pdf">Empirical Analysis of Predictive Algorithms for
- * Collaborative Filtering</a>.</p>
- *
- * <p>A scaling factor is computed for each item by dividing the total number of users by the number of users
- * expressing a preference for that item, and taking the log of that value. The log base of this calculation can be
- * controlled in the constructor. Intuitively, the right value for the base is equal to the average number of users who
- * express a preference for each item in your model. If each item has about 100 preferences on average, 100.0 is a good
- * log base.</p>
+ * Collaborative Filtering</a>.
+ * </p>
+ *
+ * <p>
+ * A scaling factor is computed for each item by dividing the total number of users by the number of users
+ * expressing a preference for that item, and taking the log of that value. The log base of this calculation
+ * can be controlled in the constructor. Intuitively, the right value for the base is equal to the average
+ * number of users who express a preference for each item in your model. If each item has about 100
+ * preferences on average, 100.0 is a good log base.
+ * </p>
*/
public final class InverseUserFrequency implements PreferenceTransform {
-
+
private final DataModel dataModel;
private final RefreshHelper refreshHelper;
private final double logBase;
private final AtomicReference<FastByIDMap<Double>> iufFactors;
-
+
/**
- * <p>Creates a {@link InverseUserFrequency} transformation. Computations use the given log base.</p>
- *
- * @param dataModel {@link DataModel} from which to calculate user frequencies
- * @param logBase calculation logarithm base
- * @throws IllegalArgumentException if dataModel is <code>null</code> or logBase is {@link Double#NaN} or <= 1.0
+ * <p>
+ * Creates a {@link InverseUserFrequency} transformation. Computations use the given log base.
+ * </p>
+ *
+ * @param dataModel
+ * {@link DataModel} from which to calculate user frequencies
+ * @param logBase
+ * calculation logarithm base
+ * @throws IllegalArgumentException
+ * if dataModel is <code>null</code> or logBase is {@link Double#NaN} or <= 1.0
*/
public InverseUserFrequency(DataModel dataModel, double logBase) throws TasteException {
if (dataModel == null) {
throw new IllegalArgumentException("dataModel is null");
}
- if (Double.isNaN(logBase) || logBase <= 1.0) {
+ if (Double.isNaN(logBase) || (logBase <= 1.0)) {
throw new IllegalArgumentException("logBase is NaN or <= 1.0");
}
this.dataModel = dataModel;
@@ -80,12 +89,12 @@
this.refreshHelper.addDependency(this.dataModel);
recompute();
}
-
+
/** @return log base used in this object's calculations */
public double getLogBase() {
return logBase;
}
-
+
@Override
public float getTransformedValue(Preference pref) {
Double factor = iufFactors.get().get(pref.getItemID());
@@ -94,12 +103,12 @@
}
return pref.getValue();
}
-
+
@Override
public void refresh(Collection<Refreshable> alreadyRefreshed) {
refreshHelper.refresh(alreadyRefreshed);
}
-
+
private synchronized void recompute() throws TasteException {
Counters itemPreferenceCounts = new Counters();
int numUsers = 0;
@@ -114,16 +123,16 @@
}
FastByIDMap<Double> newIufFactors = new FastByIDMap<Double>(itemPreferenceCounts.size());
double logFactor = Math.log(logBase);
- for (Map.Entry<Long, int[]> entry : itemPreferenceCounts.getEntrySet()) {
- newIufFactors.put(entry.getKey(),
- Math.log((double) numUsers / (double) entry.getValue()[0]) / logFactor);
+ for (Map.Entry<Long,int[]> entry : itemPreferenceCounts.getEntrySet()) {
+ newIufFactors.put(entry.getKey(), Math.log((double) numUsers / (double) entry.getValue()[0])
+ / logFactor);
}
iufFactors.set(newIufFactors);
}
-
+
@Override
public String toString() {
return "InverseUserFrequency[logBase:" + logBase + ']';
}
-
+
}
Modified: lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/ZScore.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/ZScore.java?rev=909912&r1=909911&r2=909912&view=diff
==============================================================================
--- lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/ZScore.java (original)
+++ lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/ZScore.java Sat Feb 13 20:54:05 2010
@@ -17,6 +17,8 @@
package org.apache.mahout.cf.taste.impl.transforms;
+import java.util.Collection;
+
import org.apache.mahout.cf.taste.common.Refreshable;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.Cache;
@@ -29,28 +31,30 @@
import org.apache.mahout.cf.taste.model.PreferenceArray;
import org.apache.mahout.cf.taste.transforms.PreferenceTransform;
-import java.util.Collection;
-
/**
- * <p>Normalizes preference values for a user by converting them to
- * <a href="http://mathworld.wolfram.com/z-Score.html">"z-scores"</a>.
- * This process normalizes preference values to adjust for variation in mean and variance of a user's preferences.</p>
- *
- * <p>Imagine two users, one who tends to rate every movie he/she sees four or five stars, and another who uses the full
- * one to five star range when assigning ratings. This transform normalizes away the difference in scale used by the two
- * users so that both have a mean preference of 0.0 and a standard deviation of 1.0.</p>
+ * <p>
+ * Normalizes preference values for a user by converting them to <a
+ * href="http://mathworld.wolfram.com/z-Score.html">"z-scores"</a>. This process normalizes preference values
+ * to adjust for variation in mean and variance of a user's preferences.
+ * </p>
+ *
+ * <p>
+ * Imagine two users, one who tends to rate every movie he/she sees four or five stars, and another who uses
+ * the full one to five star range when assigning ratings. This transform normalizes away the difference in
+ * scale used by the two users so that both have a mean preference of 0.0 and a standard deviation of 1.0.
+ * </p>
*/
public final class ZScore implements PreferenceTransform {
-
+
private final DataModel dataModel;
- private final Cache<Long, RunningAverageAndStdDev> meanAndStdevs;
-
+ private final Cache<Long,RunningAverageAndStdDev> meanAndStdevs;
+
public ZScore(DataModel dataModel) {
this.dataModel = dataModel;
- this.meanAndStdevs = new Cache<Long, RunningAverageAndStdDev>(new MeanStdevRetriever());
+ this.meanAndStdevs = new Cache<Long,RunningAverageAndStdDev>(new MeanStdevRetriever());
refresh(null);
}
-
+
@Override
public float getTransformedValue(Preference pref) throws TasteException {
RunningAverageAndStdDev meanAndStdev = meanAndStdevs.get(pref.getUserID());
@@ -62,21 +66,21 @@
}
return 0.0f;
}
-
+
@Override
public void refresh(Collection<Refreshable> alreadyRefreshed) {
meanAndStdevs.clear();
alreadyRefreshed = RefreshHelper.buildRefreshed(alreadyRefreshed);
RefreshHelper.maybeRefresh(alreadyRefreshed, dataModel);
}
-
+
@Override
public String toString() {
return "ZScore";
}
-
- private class MeanStdevRetriever implements Retriever<Long, RunningAverageAndStdDev> {
-
+
+ private class MeanStdevRetriever implements Retriever<Long,RunningAverageAndStdDev> {
+
@Override
public RunningAverageAndStdDev get(Long userID) throws TasteException {
RunningAverageAndStdDev running = new FullRunningAverageAndStdDev();
@@ -88,5 +92,5 @@
return running;
}
}
-
+
}
Modified: lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/model/DataModel.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/model/DataModel.java?rev=909912&r1=909911&r2=909912&view=diff
==============================================================================
--- lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/model/DataModel.java (original)
+++ lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/model/DataModel.java Sat Feb 13 20:54:05 2010
@@ -17,6 +17,8 @@
package org.apache.mahout.cf.taste.model;
+import java.util.List;
+
import org.apache.mahout.cf.taste.common.NoSuchItemException;
import org.apache.mahout.cf.taste.common.NoSuchUserException;
import org.apache.mahout.cf.taste.common.Refreshable;
@@ -24,105 +26,141 @@
import org.apache.mahout.cf.taste.impl.common.FastIDSet;
import org.apache.mahout.cf.taste.impl.common.LongPrimitiveIterator;
-import java.util.List;
-
/**
- * <p>Implementations represent a repository of information about users and their associated {@link Preference}s
- * for items.</p>
+ * <p>
+ * Implementations represent a repository of information about users and their associated {@link Preference}s
+ * for items.
+ * </p>
*/
public interface DataModel extends Refreshable {
-
+
/**
* @return all user IDs in the model, in order
- * @throws TasteException if an error occurs while accessing the data
+ * @throws TasteException
+ * if an error occurs while accessing the data
*/
LongPrimitiveIterator getUserIDs() throws TasteException;
-
+
/**
- * @param userID ID of user to get prefs for
+ * @param userID
+ * ID of user to get prefs for
* @return user's preferences, ordered by item ID
- * @throws NoSuchUserException if the user does not exist
- * @throws TasteException if an error occurs while accessing the data
+ * @throws NoSuchUserException
+ * if the user does not exist
+ * @throws TasteException
+ * if an error occurs while accessing the data
*/
PreferenceArray getPreferencesFromUser(long userID) throws TasteException;
-
+
/**
- * @param userID ID of user to get prefs for
+ * @param userID
+ * ID of user to get prefs for
* @return IDs of items user expresses a preference for
- * @throws NoSuchUserException if the user does not exist
- * @throws TasteException if an error occurs while accessing the data
+ * @throws NoSuchUserException
+ * if the user does not exist
+ * @throws TasteException
+ * if an error occurs while accessing the data
*/
FastIDSet getItemIDsFromUser(long userID) throws TasteException;
-
+
/**
* @return a {@link List} of all item IDs in the model, in order
- * @throws TasteException if an error occurs while accessing the data
+ * @throws TasteException
+ * if an error occurs while accessing the data
*/
LongPrimitiveIterator getItemIDs() throws TasteException;
-
+
/**
- * @param itemID item ID
+ * @param itemID
+ * item ID
* @return all existing {@link Preference}s expressed for that item, ordered by user ID, as an array
- * @throws NoSuchItemException if the item does not exist
- * @throws TasteException if an error occurs while accessing the data
+ * @throws NoSuchItemException
+ * if the item does not exist
+ * @throws TasteException
+ * if an error occurs while accessing the data
*/
PreferenceArray getPreferencesForItem(long itemID) throws TasteException;
-
+
/**
* Retrieves the preference value for a single user and item.
- *
- * @param userID user ID to get pref value from
- * @param itemID item ID to get pref value for
+ *
+ * @param userID
+ * user ID to get pref value from
+ * @param itemID
+ * item ID to get pref value for
* @return preference value from the given user for the given item or null if none exists
- * @throws NoSuchUserException if the user does not exist
- * @throws TasteException if an error occurs while accessing the data
+ * @throws NoSuchUserException
+ * if the user does not exist
+ * @throws TasteException
+ * if an error occurs while accessing the data
*/
Float getPreferenceValue(long userID, long itemID) throws TasteException;
-
+
/**
- * @return total number of items known to the model. This is generally the union of all items
- * preferred by at least one user but could include more.
- * @throws TasteException if an error occurs while accessing the data
+ * @return total number of items known to the model. This is generally the union of all items preferred by
+ * at least one user but could include more.
+ * @throws TasteException
+ * if an error occurs while accessing the data
*/
int getNumItems() throws TasteException;
-
+
/**
* @return total number of users known to the model.
- * @throws TasteException if an error occurs while accessing the data
+ * @throws TasteException
+ * if an error occurs while accessing the data
*/
int getNumUsers() throws TasteException;
-
+
/**
- * @param itemIDs item IDs to check for
+ * @param itemIDs
+ * item IDs to check for
* @return the number of users who have expressed a preference for all of the items
- * @throws TasteException if an error occurs while accessing the data
- * @throws IllegalArgumentException if itemIDs is null, empty, or larger than 2 elements since currently only queries
- * of up to 2 items are needed and supported
- * @throws NoSuchItemException if an item does not exist
+ * @throws TasteException
+ * if an error occurs while accessing the data
+ * @throws IllegalArgumentException
+ * if itemIDs is null, empty, or larger than 2 elements since currently only queries of up to 2
+ * items are needed and supported
+ * @throws NoSuchItemException
+ * if an item does not exist
*/
int getNumUsersWithPreferenceFor(long... itemIDs) throws TasteException;
-
+
/**
- * <p>Sets a particular preference (item plus rating) for a user.</p>
- *
- * @param userID user to set preference for
- * @param itemID item to set preference for
- * @param value preference value
- * @throws NoSuchItemException if the item does not exist
- * @throws NoSuchUserException if the user does not exist
- * @throws TasteException if an error occurs while accessing the data
+ * <p>
+ * Sets a particular preference (item plus rating) for a user.
+ * </p>
+ *
+ * @param userID
+ * user to set preference for
+ * @param itemID
+ * item to set preference for
+ * @param value
+ * preference value
+ * @throws NoSuchItemException
+ * if the item does not exist
+ * @throws NoSuchUserException
+ * if the user does not exist
+ * @throws TasteException
+ * if an error occurs while accessing the data
*/
void setPreference(long userID, long itemID, float value) throws TasteException;
-
+
/**
- * <p>Removes a particular preference for a user.</p>
- *
- * @param userID user from which to remove preference
- * @param itemID item to remove preference for
- * @throws NoSuchItemException if the item does not exist
- * @throws NoSuchUserException if the user does not exist
- * @throws TasteException if an error occurs while accessing the data
+ * <p>
+ * Removes a particular preference for a user.
+ * </p>
+ *
+ * @param userID
+ * user from which to remove preference
+ * @param itemID
+ * item to remove preference for
+ * @throws NoSuchItemException
+ * if the item does not exist
+ * @throws NoSuchUserException
+ * if the user does not exist
+ * @throws TasteException
+ * if an error occurs while accessing the data
*/
void removePreference(long userID, long itemID) throws TasteException;
-
+
}
Modified: lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/model/IDMigrator.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/model/IDMigrator.java?rev=909912&r1=909911&r2=909912&view=diff
==============================================================================
--- lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/model/IDMigrator.java (original)
+++ lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/model/IDMigrator.java Sat Feb 13 20:54:05 2010
@@ -20,57 +20,68 @@
import org.apache.mahout.cf.taste.common.TasteException;
/**
- * <p>Mahout 0.2 changed the framework to operate only in terms of numeric (long) ID values
- * for users and items. This is, obviously, not compatible with applications that used other
- * key types -- most commonly {@link String}. Implementation of this class provide support for
- * mapping String to longs and vice versa in order to provide a smoother migration path to
- * applications that must still use strings as IDs.</p>
- *
- * <p>The mapping from strings to 64-bit numeric values is fixed here, to provide a standard
- * implementation that is 'portable' or reproducible outside the framework easily. See
- * {@link #toLongID(String)}.</p>
- *
- * <p>Because this mapping is deterministically computable, it does not need to be stored. Indeed,
- * subclasses' job is to store the reverse mapping. There are an infinite number of strings but only
- * a fixed number of longs, so, it is possible for two strings to map to the same value. Subclasses
- * do not treat this as an error but rather retain only the most recent mapping, overwriting a previous
- * mapping. The probability of collision in a 64-bit space is quite small, but not zero. However,
- * in the context of a collaborative filtering problem, the consequence of a collision is small, at worst
- * -- perhaps one user receives another recommendations.</p>
- *
+ * <p>
+ * Mahout 0.2 changed the framework to operate only in terms of numeric (long) ID values for users and items.
+ * This is, obviously, not compatible with applications that used other key types -- most commonly
+ * {@link String}. Implementation of this class provide support for mapping String to longs and vice versa in
+ * order to provide a smoother migration path to applications that must still use strings as IDs.
+ * </p>
+ *
+ * <p>
+ * The mapping from strings to 64-bit numeric values is fixed here, to provide a standard implementation that
+ * is 'portable' or reproducible outside the framework easily. See {@link #toLongID(String)}.
+ * </p>
+ *
+ * <p>
+ * Because this mapping is deterministically computable, it does not need to be stored. Indeed, subclasses'
+ * job is to store the reverse mapping. There are an infinite number of strings but only a fixed number of
+ * longs, so, it is possible for two strings to map to the same value. Subclasses do not treat this as an
+ * error but rather retain only the most recent mapping, overwriting a previous mapping. The probability of
+ * collision in a 64-bit space is quite small, but not zero. However, in the context of a collaborative
+ * filtering problem, the consequence of a collision is small, at worst -- perhaps one user receives another
+ * recommendations.
+ * </p>
+ *
* @since 0.2
*/
public interface IDMigrator {
-
+
/**
- * @return the top 8 bytes of the MD5 hash of the bytes of the given {@link String}'s UTF-8 encoding as a long.
- * @throws TasteException if an error occurs while storing the mapping
+ * @return the top 8 bytes of the MD5 hash of the bytes of the given {@link String}'s UTF-8 encoding as a
+ * long.
+ * @throws TasteException
+ * if an error occurs while storing the mapping
*/
long toLongID(String stringID);
-
+
/**
* @return the string ID most recently associated with the given long ID, or null if doesn't exist
- * @throws TasteException if an error occurs while retrieving the mapping
+ * @throws TasteException
+ * if an error occurs while retrieving the mapping
*/
String toStringID(long longID) throws TasteException;
-
+
/**
- * Stores the reverse long-to-String mapping in some kind of backing store. Note that this must
- * be called directly (or indirectly through {@link #initialize(Iterable)}) for every String that
- * might be encountered in the application, or else the mapping will not be known.
- *
- * @param longID long ID
- * @param stringID string ID that maps to/from that long ID
- * @throws TasteException if an error occurs while saving the mapping
+ * Stores the reverse long-to-String mapping in some kind of backing store. Note that this must be called
+ * directly (or indirectly through {@link #initialize(Iterable)}) for every String that might be encountered
+ * in the application, or else the mapping will not be known.
+ *
+ * @param longID
+ * long ID
+ * @param stringID
+ * string ID that maps to/from that long ID
+ * @throws TasteException
+ * if an error occurs while saving the mapping
*/
void storeMapping(long longID, String stringID) throws TasteException;
-
+
/**
- * Make the mapping aware of the given string IDs. This must be called initially before
- * the implementation is used, or else it will not be aware of reverse long-to-String mappings.
- *
- * @throws TasteException if an error occurs while storing the mappings
+ * Make the mapping aware of the given string IDs. This must be called initially before the implementation
+ * is used, or else it will not be aware of reverse long-to-String mappings.
+ *
+ * @throws TasteException
+ * if an error occurs while storing the mappings
*/
void initialize(Iterable<String> stringIDs) throws TasteException;
-
+
}
Modified: lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/model/JDBCDataModel.java
URL: http://svn.apache.org/viewvc/lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/model/JDBCDataModel.java?rev=909912&r1=909911&r2=909912&view=diff
==============================================================================
--- lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/model/JDBCDataModel.java (original)
+++ lucene/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/model/JDBCDataModel.java Sat Feb 13 20:54:05 2010
@@ -17,27 +17,27 @@
package org.apache.mahout.cf.taste.model;
+import javax.sql.DataSource;
+
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.FastByIDMap;
import org.apache.mahout.cf.taste.impl.common.FastIDSet;
-import javax.sql.DataSource;
-
public interface JDBCDataModel extends DataModel {
-
+
/**
* @return {@link DataSource} underlying this model
*/
DataSource getDataSource();
-
+
/**
- * Hmm, should this exist elsewhere? seems like most relevant for a DB
- * implementation, which is not in memory, which might want to export to memory.
- *
+ * Hmm, should this exist elsewhere? seems like most relevant for a DB implementation, which is not in
+ * memory, which might want to export to memory.
+ *
* @return all user preference data
*/
FastByIDMap<PreferenceArray> exportWithPrefs() throws TasteException;
-
+
FastByIDMap<FastIDSet> exportWithIDsOnly() throws TasteException;
-
+
}
\ No newline at end of file