Apriori { public Set<ItemsetWithCount> getItemsets(List<Set<Integer>> transactions, Double support) { Set<ItemsetWithCount> ret = new HashSet<>(); int minSupportCount = (int) (support * transactions.size()); HashMap<Integer, Integer> itemCounts = new HashMap<>(); for (Set<Integer> t : transactions) { for (int i : t) { itemCounts.compute(i, (k, v) -> v == null ? 1 : v + 1); } } for (Map.Entry<Integer, Integer> e : itemCounts.entrySet()) { if (e.getValue() >= minSupportCount) { HashSet<Integer> singletonSet = new HashSet<>(); singletonSet.add(e.getKey()); ret.add(new ItemsetWithCount(singletonSet, e.getValue())); } } if (ret.size() == 0) { return ret; } HashMap<Set<Integer>, Integer> pairCandidateCounts = new HashMap<>(); for (Set<Integer> t : transactions) { List<Integer> txList = Lists.newArrayList(t); for (int i = 0; i < t.size(); ++i) { for (int j = i + 1; j < t.size(); ++j) { HashSet<Integer> pairSet = new HashSet<>(); pairSet.add(txList.get(i)); pairSet.add(txList.get(j)); pairCandidateCounts.compute(pairSet, (k, v) -> v == null ? 1 : v + 1); } } } List<ItemsetWithCount> pairItemsets = new ArrayList<>(); for (Map.Entry<Set<Integer>, Integer> e : pairCandidateCounts.entrySet()) { if (e.getValue() >= minSupportCount) { ItemsetWithCount ic = new ItemsetWithCount(e.getKey(), e.getValue()); ret.add(ic); pairItemsets.add(ic); } } if (pairItemsets.isEmpty()) { return ret; } List<ItemsetWithCount> prevRoundItemsets = pairItemsets; Set<Integer> infrequentIndex = new HashSet<>(); int newSize = 3; while (true) { Set<Set<Integer>> candidates = genCandidates(prevRoundItemsets, newSize); prevRoundItemsets = filterItems(transactions, candidates, infrequentIndex, minSupportCount); if (prevRoundItemsets.isEmpty()) { return ret; } else { ret.addAll(prevRoundItemsets); newSize += 1; } } }  Set<ItemsetWithCount> getItemsets(List<Set<Integer>> transactions,
                                             Double support);  }
@Test public void testFPFromPaper() { List<Set<Integer>> txns = new ArrayList<>(); txns.add(intIfy("f, a, c, d, g, i, m, p")); txns.add(intIfy("a, b, c, f, l, m, o")); txns.add(intIfy("b, f, h, j, o")); txns.add(intIfy("b, c, k, s, p")); txns.add(intIfy("a, f, c, e, l, p, m, n")); Apriori fp = new Apriori(); Set<ItemsetWithCount> itemsets = fp.getItemsets(txns, .6); assertEquals(18, itemsets.size()); }
@Test public void simpleTest() { List<Set<Integer>> txns = new ArrayList<>(); txns.add(intIfy("a, b, c")); txns.add(intIfy("a, b")); txns.add(intIfy("a")); Apriori fp = new Apriori(); Set<ItemsetWithCount> itemsets = fp.getItemsets(txns, .7); assertEquals(3, itemsets.size()); }