我使用 Hadoop Streaming 在 Apache Spark 和 Hadoop MapReduce 中实现了 AES 算法。
我知道它与 Apriori 不一样,但您可以尝试使用我的方法。
使用 Hadoop Streming MapReduce 实现的 AES 简单示例。
Project structure for AES Hadoop Streaming
1n_reducer.py / 1n_combiner 是相同的代码,但没有约束。
import sys
CONSTRAINT = 1000
def do_reduce(word, _values):
return word, sum(_values)
prev_key = None
values = []
for line in sys.stdin:
key, value = line.split("\t")
if key != prev_key and prev_key is not None:
result_key, result_value = do_reduce(prev_key, values)
if result_value > CONSTRAINT:
print(result_key + "\t" + str(result_value))
values = []
prev_key = key
values.append(int(value))
if prev_key is not None:
result_key, result_value = do_reduce(prev_key, values)
if result_value > CONSTRAINT:
print(result_key + "\t" + str(result_value))
base_mapper.py:
import sys
def count_usage():
for line in sys.stdin:
elements = line.rstrip("\n").rsplit(",")
for item in elements:
print("{item}\t{count}".format(item=item, count=1))
if __name__ == "__main__":
count_usage()
2n_mapper.py 使用上一次迭代的结果。
在回答您的问题时,您可以读取先前迭代的输出以形成项集。
import itertools
import sys
sys.path.append('.')
N_DIM = 2
def get_2n_items():
items = set()
with open("part-00000") as inf:
for line in inf:
parts = line.split('\t')
if len(parts) > 1:
items.add(parts[0])
return items
def count_usage_of_2n_items():
all_items_set = get_2n_items()
for line in sys.stdin:
items = line.rstrip("\n").rsplit(",") # 74743 43355 53554
exist_in_items = set()
for item in items:
if item in all_items_set:
exist_in_items.add(item)
for combination in itertools.combinations(exist_in_items, N_DIM):
combination = sorted(combination)
print("{el1},{el2}\t{count}".format(el1=combination[0], el2=combination[1], count=1))
if __name__ == "__main__":
count_usage_of_2n_items()
根据我的经验,如果唯一组合(项目集)的数量太大(100K+),Apriori 算法不适合 Hadoop。
如果您找到了使用 Hadoop MapReduce(流式处理或 Java MapReduce 实现)实现 Apriori 算法的优雅解决方案,请与社区分享。
PS。如果您需要更多代码 sn-ps 请索取。