FP-Growth 是一種常用於關聯分析、挖掘頻繁項的算法。與 Apriori 相比,它以「前綴樹」的形式表征數據,減少了掃描事務數據庫的次數,並通過遞歸生成條件 FP-tree 來挖掘頻繁項。然而,面對大數據量時,FP-Growth 生成的 FP-tree 往往龐大到無法放入內存,挖掘出的頻繁項也可能多到呈指數級。本文將剖析如何並行化 FP-Growth,並解讀 Mahout 中對應的源碼實現。
並行化 FP-Growth 的方法有很多,最早提出用 MapReduce 並行化的應是 Google Beijing Research 的 Haoyuan Li 等人。他們用三次 MapReduce 來完成,整個過程大致分為五個步驟。
為均衡整個集群的讀寫性能,將事務數據庫分成若干數據片段(shard),存儲到 P 個節點中。
與 WordCount 類似,通過一次 MapReduce 計算每個項(item)的支持度。每個 mapper 從 HDFS 取得若干數據片段,輸入為 <key, value=Ti>,Ti 表示片段中的一條數據。對於 Ti 中的每個項 aj,mapper 輸出 <key=aj, value=1>。所有 key=aj 的鍵值對會被分配到同一個 reducer,其輸入為 <key=aj, value={1, 1, ... , 1}>,只需求和後輸出 <key=aj, value=sum>。最終得到一張按支持度遞減排序的列表,稱為 F-List。
圖1
將 F-List 中的項分為 Q 個組(group),每組有一個唯一的 group-id,把所有項及其對應的 group-id 記為 G-List。
這是並行化的關鍵,也是相對難懂的部分,用到一次 MapReduce。每個 mapper 輸入同樣是 <key, value=Ti>,處理前先讀取 G-List。G-List 本質上是一張 Hashmap,鍵是項,值是 group-id,佔用空間不大,可放入內存。從 Ti 的最後一項向前(從右向左)掃描,若 aL 在 G-List 中對應的 group-id 是第一次被掃描,則輸出 {a0,a1,…,aL},否則不輸出。以圖1數據為例,若支持度阈值為 1、Q 為 3,可得到的 G-List 如圖2所示。
圖2
其中第三列是 group-id。假如 mapper 輸入是 {牛奶,雞蛋,面包,薯片},從最後一項薯片開始掃描,其 group-id 首次出現,輸出 <key=1,value={牛奶,雞蛋,面包,薯片}>;接下來面包、雞蛋的 group-id 與薯片相同,不輸出;第一項牛奶的 group-id 未曾出現,輸出 <key=2,value={牛奶}>。
所有 group-id 相同的數據會推送到同一個 reducer,其輸入為 <key=group-id,value={{ValueList1},{ValueList2},…}>。reducer 在本地構建 FP-tree,像傳統算法那樣遞歸構建條件 FP-tree 並挖掘頻繁模式。不同的是,它並不直接輸出所有頻繁模式,而是把它們放入一個大小為 K、按支持度排序的大根堆,最後輸出 K 個支持度較高的頻繁模式:<key=item,reduce={包含該 item 的 Top K Frequent Patterns}>。
上一步挖掘出的 Top K Frequent Patterns 已包含所有頻繁模式,但由於是按 groupID 劃分數據,同一個 key=item 對應的頻繁模式會散落在多個不同 groupID 的 reduce 節點上。為合並所有 key=item 的鍵值對,可利用 MapReduce 默認對 key 排序的特點:依次把 Top K Frequent Patterns 中的每個 item 作為 key,輸出包含該 key 的這一條頻繁模式。於是每個 mapper 輸出 <key=item, value={該節點上包含該 item 的頻繁模式}>,reducer 匯總所有 mapper 的輸出,得到 <key=item, value={包含該 item 的所有頻繁模式}>。
Mahout 提供了機器學習領域諸多經典算法的實現。Mahout 0.9 之後的版本已移除 Parallel FP-Growth,本文分析 Mahout 0.8 中的實現。
圖3
FPGrowthDriver.java
FPGrowthDriver 是 FP-Growth 算法的驅動類,繼承自 AbstractJob。運行 Hadoop 任務通常通過命令行執行 bin/hadoop 腳本並傳入參數,ToolRunner 中的 GenericOptionsParser 可獲取這些參數,AbstractJob 封裝了 addInputOption、addOutputOption、parseArguments 等方法。params 對象存儲算法所需的所有參數。FPGrowthDriver 根據參數判斷:順序執行則調用本文件的 runFPGrowth,並行執行則調用 PFPGrowth.java 的 runPFPGrowth。
public final class FPGrowthDriver extends AbstractJob {
private static final Logger log = LoggerFactory.getLogger(FPGrowthDriver.class);
private FPGrowthDriver() {}
public static void main(String[] args) throws Exception {
ToolRunner.run(new Configuration(), new FPGrowthDriver(), args);
}
@Override
public int run(String[] args) throws Exception {
addInputOption();
addOutputOption();
addOption("minSupport", "s", "(Optional) The minimum number of times a co-occurrence must be present. Default Value: 3", "3");
addOption("maxHeapSize", "k", "(Optional) Maximum Heap Size k. Default value: 50", "50");
addOption("numGroups", "g", "(Optional) Number of groups. Default Value:" + PFPGrowth.NUM_GROUPS_DEFAULT, Integer.toString(PFPGrowth.NUM_GROUPS_DEFAULT));
addOption("splitterPattern", "regex", "Regular Expression pattern used to split. ", "[ ,\t]*[,|\t][ ,\t]*");
addOption("numTreeCacheEntries", "tc", "(Optional) Number of entries in the tree cache. Default Value:5", "5");
addOption("method", "method", "Method of processing: sequential|mapreduce", "sequential");
addOption("encoding", "e", "(Optional) The file encoding. Default value: UTF-8", "UTF-8");
addFlag("useFPG2", "2", "Use an alternate FPG implementation");
if (parseArguments(args) == null) { return -1; }
Parameters params = new Parameters();
// ... 各項參數設置省略 ...
String classificationMethod = getOption("method");
if ("sequential".equalsIgnoreCase(classificationMethod)) {
runFPGrowth(params);
} else if ("mapreduce".equalsIgnoreCase(classificationMethod)) {
Configuration conf = new Configuration();
HadoopUtil.delete(conf, outputDir);
PFPGrowth.runPFPGrowth(params);
}
return 0;
}
}
PFPGrowth.java
PFPGrowth 是並行化 FP-Growth 的驅動類。runPFPGrowth(params) 初始化 Configuration 後調用 runPFPGrowth(params, conf),後者包含並行算法的五個關鍵步驟:startParallelCounting 對應 Step1、Step2,其輸出被 readFList() 和 saveList() 用於生成 FList;再按 NUM_GROUPS 計算每組所含項數並存入 params;startParallelFPGrowth 對應 Step3、Step4;startAggregating 對應 Step5。
public static void runPFPGrowth(Parameters params, Configuration conf) throws IOException, InterruptedException, ClassNotFoundException {
conf.set("io.serializations", "org.apache.hadoop.io.serializer.JavaSerialization," + "org.apache.hadoop.io.serializer.WritableSerialization");
startParallelCounting(params, conf); // 對應 Step1 和 Step2
List<Pair<String,Long>> fList = readFList(params);
saveFList(fList, params, conf);
int numGroups = params.getInt(NUM_GROUPS, NUM_GROUPS_DEFAULT);
int maxPerGroup = fList.size() / numGroups;
if (fList.size() % numGroups != 0) { maxPerGroup++; }
params.set(MAX_PER_GROUP, Integer.toString(maxPerGroup));
startParallelFPGrowth(params, conf); // 對應 Step3 和 Step4
startAggregating(params, conf); // 對應 Step5
}
startParallelCounting 初始化一個 Job,調用 ParallelCountingMapper 和 ParallelCountingReducer 完成支持度統計。
public static void startParallelCounting(Parameters params, Configuration conf) throws IOException, InterruptedException, ClassNotFoundException {
conf.set(PFP_PARAMETERS, params.toString());
conf.set("mapred.compress.map.output", "true");
conf.set("mapred.output.compression.type", "BLOCK");
String input = params.get(INPUT);
Job job = new Job(conf, "Parallel Counting Driver running over input: " + input);
job.setJarByClass(PFPGrowth.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(LongWritable.class);
FileInputFormat.addInputPath(job, new Path(input));
Path outPath = new Path(params.get(OUTPUT), PARALLEL_COUNTING);
FileOutputFormat.setOutputPath(job, outPath);
HadoopUtil.delete(conf, outPath);
job.setInputFormatClass(TextInputFormat.class);
job.setMapperClass(ParallelCountingMapper.class);
job.setCombinerClass(ParallelCountingReducer.class);
job.setReducerClass(ParallelCountingReducer.class);
job.setOutputFormatClass(SequenceFileOutputFormat.class);
boolean succeeded = job.waitForCompletion(true);
if (!succeeded) { throw new IllegalStateException("Job failed!"); }
}
ParallelCountingMapper.java
map 方法輸入是字節偏移量與事務數據庫的某行數據。同一行中重復出現的項只算一次,所以先 split 再存進 HashSet。輸出為 <key=item, value=one>。
public class ParallelCountingMapper extends Mapper<LongWritable,Text,Text,LongWritable> {
private static final LongWritable ONE = new LongWritable(1);
private Pattern splitter;
@Override
protected void map(LongWritable offset, Text input, Context context) throws IOException, InterruptedException {
String[] items = splitter.split(input.toString());
Set<String> uniqueItems = Sets.newHashSet(Arrays.asList(items));
for (String item : uniqueItems) {
if (item.trim().isEmpty()) { continue; }
context.setStatus("Parallel Counting Mapper: " + item);
context.write(new Text(item), ONE);
}
}
@Override
protected void setup(Context context) throws IOException, InterruptedException {
super.setup(context);
Parameters params = new Parameters(context.getConfiguration().get(PFPGrowth.PFP_PARAMETERS, ""));
splitter = Pattern.compile(params.get(PFPGrowth.SPLIT_PATTERN, PFPGrowth.SPLITTER.toString()));
}
}
ParallelCountingReducer.java
reduce 輸入是 <key=item, value={one, one, ...}>。所有 key=item 分配到一台機器,只需遍歷求和即得支持度。
public class ParallelCountingReducer extends Reducer<Text,LongWritable,Text,LongWritable> {
@Override
protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
long sum = 0;
for (LongWritable value : values) {
context.setStatus("Parallel Counting Reducer :" + key);
sum += value.get();
}
context.write(key, new LongWritable(sum));
}
}
PFPGrowth.java(readFList / saveFList)
readFList 中,Pair 實現了 Comparable 與 Serializable,first 表示 item、second 表示支持度;PriorityQueue 是以平衡二叉樹實現的小頂堆,初始化時指定 Comparator,按 Pair 第一個元素排序,相等則按第二個元素排序。通過 SequenceFileDirIterable 遍歷上次 MapReduce 的輸出,邊加入 PriorityQueue 邊排序,最後逐一取出放入 fList。因此 fList 是一個按支持度遞減的列表。
public static List<Pair<String,Long>> readFList(Parameters params) {
int minSupport = Integer.valueOf(params.get(MIN_SUPPORT, "3"));
Configuration conf = new Configuration();
Path parallelCountingPath = new Path(params.get(OUTPUT), PARALLEL_COUNTING);
PriorityQueue<Pair<String,Long>> queue = new PriorityQueue<Pair<String,Long>>(11,
new Comparator<Pair<String,Long>>() {
@Override
public int compare(Pair<String,Long> o1, Pair<String,Long> o2) {
int ret = o2.getSecond().compareTo(o1.getSecond());
if (ret != 0) { return ret; }
return o1.getFirst().compareTo(o2.getFirst());
}
});
for (Pair<Text,LongWritable> record : new SequenceFileDirIterable<Text,LongWritable>(new Path(parallelCountingPath, FILE_PATTERN), PathType.GLOB, null, null, true, conf)) {
long value = record.getSecond().get();
if (value >= minSupport) { queue.add(new Pair<String,Long>(record.getFirst().toString(), value)); }
}
List<Pair<String,Long>> fList = Lists.newArrayList();
while (!queue.isEmpty()) { fList.add(queue.poll()); }
return fList;
}
由於 fList 已生成,上次 MapReduce 的輸出不再有用,saveFList 先刪除它們,再把 fList 寫入 HDFS。對於 HDFS 上的文件,DistributedCache 提供緩存功能,可在 Slave Node 計算前把文件復制到這些節點上。
public static void saveFList(Iterable<Pair<String,Long>> flist, Parameters params, Configuration conf) throws IOException {
Path flistPath = new Path(params.get(OUTPUT), F_LIST);
FileSystem fs = FileSystem.get(flistPath.toUri(), conf);
flistPath = fs.makeQualified(flistPath);
HadoopUtil.delete(conf, flistPath);
SequenceFile.Writer writer = new SequenceFile.Writer(fs, conf, flistPath, Text.class, LongWritable.class);
try {
for (Pair<String,Long> pair : flist) {
writer.append(new Text(pair.getFirst()), new LongWritable(pair.getSecond()));
}
} finally { writer.close(); }
DistributedCache.addCacheFile(flistPath.toUri(), conf);
}
startParallelFPGrowth 初始化 Job,調用 ParallelFPGrowthMapper 和 ParallelFPGrowthReducer 實現 Step3、Step4。
public static void startParallelFPGrowth(Parameters params, Configuration conf) throws IOException, InterruptedException, ClassNotFoundException {
conf.set(PFP_PARAMETERS, params.toString());
Path input = new Path(params.get(INPUT));
Job job = new Job(conf, "PFP Growth Driver running over input" + input);
job.setJarByClass(PFPGrowth.class);
job.setMapOutputKeyClass(IntWritable.class);
job.setMapOutputValueClass(TransactionTree.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(TopKStringPatterns.class);
FileInputFormat.addInputPath(job, input);
Path outPath = new Path(params.get(OUTPUT), FPGROWTH);
FileOutputFormat.setOutputPath(job, outPath);
job.setMapperClass(ParallelFPGrowthMapper.class);
job.setCombinerClass(ParallelFPGrowthCombiner.class);
job.setReducerClass(ParallelFPGrowthReducer.class);
boolean succeeded = job.waitForCompletion(true);
if (!succeeded) { throw new IllegalStateException("Job failed!"); }
}
ParallelFPGrowthMapper.java
setup 方法在 map 之前運行,調用 readFList(此處是另一個同名不同參的方法),通過 HadoopUtil.getCachedFiles(conf) 獲取緩存文件 flist,存進 fMap:item 作鍵,item 在 flist 中的位置序號作值。map 方法中,根據 splitter 切分數據,用 fMap.containsKey(item) 過濾非頻繁項,把存在項的位置序號加入 itemSet,再複製到 itemArr 並按序號遞增排序(即按支持度遞減)。之後的循環從 itemArr 末尾向前遍歷,若其 groupID 不在 groups 中,就初始化 TransactionTree,把 itemArr[0..j] 存入。groupID 由位置序號除以 maxPerGroup 得到。
public class ParallelFPGrowthMapper extends Mapper<LongWritable,Text,IntWritable,TransactionTree> {
private final OpenObjectIntHashMap<String> fMap = new OpenObjectIntHashMap<String>();
private Pattern splitter;
private int maxPerGroup;
private final IntWritable wGroupID = new IntWritable();
@Override
protected void map(LongWritable offset, Text input, Context context) throws IOException, InterruptedException {
String[] items = splitter.split(input.toString());
OpenIntHashSet itemSet = new OpenIntHashSet();
for (String item : items) {
if (fMap.containsKey(item) && !item.trim().isEmpty()) { itemSet.add(fMap.get(item)); }
}
IntArrayList itemArr = new IntArrayList(itemSet.size());
itemSet.keys(itemArr);
itemArr.sort();
OpenIntHashSet groups = new OpenIntHashSet();
for (int j = itemArr.size() - 1; j >= 0; j--) {
int item = itemArr.get(j);
int groupID = PFPGrowth.getGroup(item, maxPerGroup);
if (!groups.contains(groupID)) {
IntArrayList tempItems = new IntArrayList(j + 1);
tempItems.addAllOfFromTo(itemArr, 0, j);
wGroupID.set(groupID);
context.write(wGroupID, new TransactionTree(tempItems, 1L));
}
groups.add(groupID);
}
}
@Override
protected void setup(Context context) throws IOException, InterruptedException {
super.setup(context);
int i = 0;
for (Pair<String,Long> e : PFPGrowth.readFList(context.getConfiguration())) { fMap.put(e.getFirst(), i++); }
// ... splitter、maxPerGroup 設置省略 ...
}
}
ParallelFPGrowthReducer.java
輸入是 <key=groupID, value={TransactionTree1, ...}>。setup 獲取 params 並通過 readFList 拿到 flist,把頻繁項存入 featureReverseMap、支持度存入 freqList。reducer 內初始化一個用二維數組實現的 TransactionTree(建樹過程從略)。cTree.generateFList 遍歷這棵樹返回 frequencyList,localFList 合並結果並按支持度遞減排序。生成頻繁模式可選 FPGrowthIds.generateTopKFrequentPatterns 或 fpGrowth.generateTopKFrequentPatterns。IteratorAdapter 是適配器模式的應用,可將兩個不同類型的迭代器解耦。輸出為 <key=item, value={Top K Frequent Patterns}>。
public final class ParallelFPGrowthReducer extends Reducer<IntWritable,TransactionTree,Text,TopKStringPatterns> {
private final List<String> featureReverseMap = Lists.newArrayList();
private final LongArrayList freqList = new LongArrayList();
private int maxHeapSize = 50;
private int minSupport = 3;
private int numFeatures;
private int maxPerGroup;
private boolean useFP2;
private static final class IteratorAdapter implements Iterator<Pair<List<Integer>,Long>> {
private final Iterator<Pair<IntArrayList,Long>> innerIter;
private IteratorAdapter(Iterator<Pair<IntArrayList,Long>> transactionIter) { innerIter = transactionIter; }
@Override public boolean hasNext() { return innerIter.hasNext(); }
@Override public Pair<List<Integer>,Long> next() {
Pair<IntArrayList,Long> innerNext = innerIter.next();
return new Pair<List<Integer>,Long>(innerNext.getFirst().toList(), innerNext.getSecond());
}
@Override public void remove() { throw new UnsupportedOperationException(); }
}
@Override
protected void reduce(IntWritable key, Iterable<TransactionTree> values, Context context) throws IOException {
TransactionTree cTree = new TransactionTree();
for (TransactionTree tr : values) {
for (Pair<IntArrayList,Long> p : tr) { cTree.addPattern(p.getFirst(), p.getSecond()); }
}
List<Pair<Integer,Long>> localFList = Lists.newArrayList();
for (Entry<Integer,MutableLong> fItem : cTree.generateFList().entrySet()) {
localFList.add(new Pair<Integer,Long>(fItem.getKey(), fItem.getValue().toLong()));
}
Collections.sort(localFList, new CountDescendingPairComparator<Integer,Long>());
// 根據 useFP2 選擇 FPGrowthIds 或 FPGrowth 生成 Top K 頻繁模式(略)
}
}
TransactionTree.java
addPattern 的建樹思路與傳統 FP-Growth 一致:從根節點開始與 myList 比較,childWithAttribute 查找同名的孩子節點,若無則 addCountMode 置 false 把剩餘節點加入樹中,若有則通過 addCount 增加該 child 的支持度。
private int[] attribute; // 節點的名稱屬性
private int[] childCount; // 孩子節點計數
private int[][] nodeChildren; // 二維數組,記錄每個節點的孩子
private long[] nodeCount; // 當前節點的支持度計數
private int nodes;
private boolean representedAsList; // true 表示 List 形式,false 表示樹形式
private List<Pair<IntArrayList,Long>> transactionSet;
public int addPattern(IntArrayList myList, long addCount) {
int temp = ROOTNODEID;
int ret = 0;
boolean addCountMode = true;
for (int idx = 0; idx < myList.size(); idx++) {
int attributeValue = myList.get(idx);
int child;
if (addCountMode) {
child = childWithAttribute(temp, attributeValue);
if (child == -1) { addCountMode = false; }
else { addCount(child, addCount); temp = child; }
}
if (!addCountMode) { child = createNode(temp, attributeValue, addCount); temp = child; ret++; }
}
return ret;
}
FPGrowth.java
generateTopKFrequentPatterns 的形參包括 transactionStream、frequencyList、minSupport、k、returnableFeatures、output、updater。attributeIdMapping 過濾非頻繁項並為頻繁項分配新 id,reverseMapping 倒置映射,attributeFrequency 記錄各 id 項的支持度,returnFeatures 記錄剩餘頻繁項,最後調用 generateTopKFrequentPatterns 構建本地 FP-tree 與頭表並遍歷輸出頻繁項。需要注意,Mahout 中 FP-tree 以數組形式存儲。
public final void generateTopKFrequentPatterns(Iterator<Pair<List<A>,Long>> transactionStream,
Collection<Pair<A, Long>> frequencyList, long minSupport, int k,
Collection<A> returnableFeatures,
OutputCollector<A,List<Pair<List<A>,Long>>> output, StatusUpdater updater) throws IOException {
Map<Integer,A> reverseMapping = Maps.newHashMap();
Map<A,Integer> attributeIdMapping = Maps.newHashMap();
int id = 0;
for (Pair<A,Long> feature : frequencyList) {
A attrib = feature.getFirst();
Long frequency = feature.getSecond();
if (frequency >= minSupport) { attributeIdMapping.put(attrib, id); reverseMapping.put(id++, attrib); }
}
long[] attributeFrequency = new long[attributeIdMapping.size()];
// ... returnFeatures 構建與遞歸調用省略 ...
generateTopKFrequentPatterns(new TransactionIterator<A>(transactionStream, attributeIdMapping),
attributeFrequency, minSupport, k, reverseMapping.size(), returnFeatures,
new TopKPatternsOutputConverter<A>(output, reverseMapping), updater);
}
AggregatorMapper 的輸入是 <key, value=TopKStringPatterns>,它對每個 pattern 中的每個 item 輸出 <key=item, value={該 pattern}>,以便 reducer 分組。
public class AggregatorMapper extends Mapper<Text,TopKStringPatterns,Text,TopKStringPatterns> {
@Override
protected void map(Text key, TopKStringPatterns values, Context context) throws IOException, InterruptedException {
for (Pair<List<String>,Long> pattern : values.getPatterns()) {
for (String item : pattern.getFirst()) {
List<Pair<List<String>,Long>> patternSingularList = Lists.newArrayList();
patternSingularList.add(pattern);
context.write(new Text(item), new TopKStringPatterns(patternSingularList));
}
}
}
}
AggregatorReducer 匯總所有 key 相同的 item,按支持度遞減排序,最終輸出 Top K 個頻繁模式。
public class AggregatorReducer extends Reducer<Text,TopKStringPatterns,Text,TopKStringPatterns> {
private int maxHeapSize = 50;
@Override
protected void reduce(Text key, Iterable<TopKStringPatterns> values, Context context) throws IOException, InterruptedException {
TopKStringPatterns patterns = new TopKStringPatterns();
for (TopKStringPatterns value : values) { patterns = patterns.merge(value, maxHeapSize); }
context.write(key, patterns);
}
@Override
protected void setup(Context context) {
super.setup(context);
Parameters params = new Parameters(context.getConfiguration().get("pfp.parameters", ""));
maxHeapSize = Integer.valueOf(params.get("maxHeapSize", "50"));
}
}
並行化 FP-Growth 解決了大數據量下傳統 FP-Growth 的性能瓶頸。除此之外,還有許多優化方向,比如並行化時考慮負載均衡,或用更緊湊的表示來壓縮頻繁模式:
[1] 關聯分析:FP-Growth算法. Mark Lin. datahunter. 2014.
[2] PFP: Parallel FP-Growth for Query Recommendation. Haoyuan Li etc. RecSys '08. 2008.