我正在上 Spark 类(class),但我有点困惑。
所以有下面的代码。我知道第 1 行正在创建元组 (word, 1)。然后第 2 行按单词分组并对计数求和。
我不明白的是,第 2 行中的 X 和 Y 是什么。我们只有一个输入到 lamda 函数的数字,即来自 wordcounts 的计数列(全为 1),那么为什么是 y?
wordCounts = words.map(lambda x: (x, 1)) #outputs [('self', 1), ('employment', 1), ('building', 1)...
wordCounts2 = wordCounts.reduceByKey(lambda x, y: x + y) # outputs [('self', 111), ('an', 178), ('internet', 26)
然后,我们就有了紧随其后的这段代码。我知道它对 RDD 进行排序。确认我的理解是 X[1] 这个词和 X[2] 总数?我猜是这样,但我不是 100%
抱歉提出愚蠢的问题,但我找不到明确的解释!
wordCountsSorted = wordCounts2.map(lambda x: (x[1], x[0])).sortByKey()
请您参考如下方法:
1。为什么是 x 和 y?
做一个键值对,比如(word, 1)
现在你的键是单词,值是 1
当你做 reduceByKey 时,它会把同一个键的所有值加起来
reduceByKey(lambda x, y: x + y) 将根据作为第一个元素 word 的键对 rdd 元素进行分组,并对值求和。在此特定语句中,x 是累积 RDD 的所有值的一个元素,y 是相同关键字/词的所有其他元素。对于相同的词或相同的键,通过添加它们的值来减少值。 可能看起来像:
# [('This', 1), ('is', 2), ('a', 3), ('random', 1), ('sample.', 2), ('And', 2), ('world', 1), ('count', 2), ('word', 1), ('sample,', 1), ('that', 1), ('it', 1)]
2。让我们分解下一个关于 wordCountsSorted = wordCounts2.map(lambda x: (x[1], x[0])).sortByKey()
的问题
下一行将交换元组的元素。本质上,位置 0 的元素移动到位置 1,位置 1 的元素移动到位置 0。
reversed_tup = wordCounts2.map(lambda x: (x[1], x[0]))
输出看起来像;
# [(1, 'This'), (2, 'is'), (3, 'a'), (1, 'random'), (2, 'sample.'), (2, 'And'), (1, 'world'), (2, 'count'), (1, 'word'), (1, 'sample,'), (1, 'that'), (1, 'it')]
现在,当您执行 sortByKey 时,这些元组将使用上面提到的元组第一个元素的键进行排序。所以rdd将按照单词的数量排序。
wordCountsSorted = reversed_tup.sortByKey()
wordCountsSorted.collect()
# [(1, 'This'), (1, 'random'), (1, 'world'), (1, 'word'), (1, 'sample,'), (1, 'that'), (1, 'it'), (2, 'is'), (2, 'sample.'), (2, 'And'), (2, 'count'), (3, 'a')]
