【发布时间】:2019-12-09 15:28:49
【问题描述】:
运行此代码以在 Hadoop 集群中获取大约 10k+ CSV 文件中的数据的概率。 我正在使用 Google DataProc Cluster 来运行此代码。请告诉我如何获得预期的输出。最后一件事可能是逻辑问题或功能问题。
#!/usr/bin/env python3
"""mapper.py"""
import sys
# Get input lines from stdin
for line in sys.stdin:
# Remove spaces from beginning and end of the line
line = line.strip()
# Split it into tokens
#tokens = line.split()
#Get probability_mass values
for probability_mass in line:
print("None\t{}".format(probability_mass))
#!/usr/bin/env python3
"""reducer.py"""
import sys
from collections import defaultdict
counts = defaultdict(int)
# Get input from stdin
for line in sys.stdin:
#Remove spaces from beginning and end of the line
line = line.strip()
# skip empty lines
if not line:
continue
# parse the input from mapper.py
k,v = line.split('\t', 1)
counts[v] += 1
total = sum(counts.values())
probability_mass = {k:v/total for k,v in counts.items()}
print(probability_mass)
我的 CSV 文件如下所示。
probability_mass
10
10
60
10
30
Expected output Probability of each number
{10: 0.6, 60: 0.2, 30: 0.2}
but result still show like this
{1:0} {0:0} {3:0} {6:0} {1:0} {6:0}
我会将这个命令保存在 nano 中,然后运行它。
yarn jar /usr/lib/hadoop-mapreduce/hadoop-streaming.jar \
-D mapred.output.key.comparator.class=org.apache.hadoop.mapred.lib.KeyFieldBasedComparator \
-D mapred.text.key.comparator.options=-n \
-files mapper.py,reducer.py \
-mapper "python mapper.py" \
-reducer "python reducer.py" \
-input /tmp/data.csv \
-output /tmp/output
【问题讨论】:
-
通过为每个映射输出提供相同的键,您可以保证它们都命中同一个 reducer,从而消除了 MapReduce 的要点。您需要事先进行一项单独的工作来计算记录总数(或者省去麻烦并使用 Spark 之类的工具)。
-
@Ben Even Spark 会强制执行此操作
-
请说明你是如何运行这段代码和你的输入文件的
-
@cricket_007 是的,但他们可能会发现以一种无法做到这一点的方式编写更容易。
标签: python python-3.x hadoop mapreduce hadoop-streaming