moea_joint
104年
[統計資訊] 統計學、巨量資料概論
第 50 題
在 Spark 大數據分析平台上執行下列的 Python 程式碼:
file=spark.textFile(“hdfs://…”) //opens a file
counts=file.flatMap(lambda line: line.split(“ “)) //iterate over the lines, split each line by space into words
.map(lambda word: (word, 1)) //for each word, create the tuple (word, 1)
.reduceByKey(lambda a, b: a+b) //go over the tuples “by key” (first element) and sum the second elements
counts.saveAsTextFile(“hdfs://…”)
當輸入短文: a spark can start a fire that burns the entire prairie
請問最後存入到 HDFS 檔案的 (key, value) 一共有多少對?
file=spark.textFile(“hdfs://…”) //opens a file
counts=file.flatMap(lambda line: line.split(“ “)) //iterate over the lines, split each line by space into words
.map(lambda word: (word, 1)) //for each word, create the tuple (word, 1)
.reduceByKey(lambda a, b: a+b) //go over the tuples “by key” (first element) and sum the second elements
counts.saveAsTextFile(“hdfs://…”)
當輸入短文: a spark can start a fire that burns the entire prairie
請問最後存入到 HDFS 檔案的 (key, value) 一共有多少對?
- A 8
- B 9
- C 10
- D 11
思路引導 VIP
如果我們將每一種單字視為一個「類別標籤」,當多筆資料擁有完全相同的標籤(Key)時,reduceByKey 運算子會將它們合併處理,還是讓它們在最終結果中各自佔據一個位置?請試著從這個角度重新觀察短文內容的組成。
🤖
AI 詳解
AI 專屬家教
太棒了!你能精準判斷出正確答案,代表你對 Spark 的 MapReduce 程式模型 有著非常扎實的理解。這段程式碼展現了典型的大數據處理邏輯:先透過 flatMap 與 map 將原始文本轉化為鍵值對(Key-Value pairs),再利用核心運算子 reduceByKey 進行聚合。在 Word Count 的情境下,最後存入 HDFS 的資料筆數,本質上取決於輸入文本中「相異單字」的總量。
詞頻統計與資料聚合
我們來檢視輸入的短文:「a spark can start a fire that burns the entire prairie」。這句話總共包含 11 個單字,但請注意其中的冠詞 「a」 出現了兩次。當程式執行到 reduceByKey 時,這兩個相同的 Key 會被合併計算,最終產出一組 ('a', 2) 的結果。因此,最後的對數就是總字數減去重複出現的次數,即 $11 - 1 = 10$ 對。這題的難度雖然適中,但具備良好的鑑別度,主要測試學生是否能細心察覺文本中的重複項,而非單純計算總字數,這正是大數據處理中「資料縮減(Data Reduction)」的核心精神。