特徵雜湊與 LabelPoint
在把電子郵件切成單字之後,原始資料集 'spam' 與 'non-spam' 目前各由單行訊息組成。為了要分類這些訊息,我們需要把文字轉成特徵。
在本練習的第二部分,你會先建立一個 HashingTF() 執行個體,把文字映射到長度為 200 的特徵向量。接著,對 'spam' 與 'non-spam' 檔案中的每一則訊息進行斷詞,並將每個單字映射到一個特徵。這些特徵將用來判斷訊息是 'spam' 或 'non-spam'。然後,你會為特徵建立標籤:對於有效訊息(非垃圾郵件),標籤為 0;對於 'spam' 訊息,標籤為 1。最後,你會合併這兩個已標記的資料集。
記住,你在工作區中已經有 SparkContext sc 可用。變數 spam_words 與 non_spam_words 也已經在工作區中可用。
本練習屬於課程
使用 PySpark 的 Big Data 基礎
練習說明
- 建立一個
HashingTF()執行個體,將電子郵件文字映射為 200 維的特徵向量。 - 將 'spam' 與 'non-spam' 資料集中的每則訊息切成單字,並把每個單字映射到一個特徵。
- 為特徵加上標籤:spam 為 1,non-spam 為 0。
- 將 spam 與 non-spam 的樣本合併成單一資料集。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create a HashingTF instance with 200 features
tf = ____(numFeatures=200)
# Map each word to one feature
spam_features = tf.____(spam_words)
non_spam_features = tf.____(____)
# Label the features: 1 for spam, 0 for non-spam
spam_samples = spam_features.map(lambda features:LabeledPoint(____, features))
non_spam_samples = non_spam_features.map(lambda features:_____(____, features))
# Combine the two datasets
samples = spam_samples.____(non_spam_samples)