SMS 垃圾訊息 pipeline
你已經有一段時間沒有看過 SMS 資料了。上次我們做了以下事情:
- 將文字切分成詞元(tokens)
- 移除停用字(stop words)
- 套用 hashing trick
- 將資料由計數轉換為 IDF,然後
- 訓練一個邏輯斯回歸(Logistic Regression)模型。
上述每一步都是獨立完成的。這正好很適合用 pipeline!
Pipeline 和 LogisticRegression 類別已經匯入到本次工作階段中,所以你不需要再擔心匯入問題!
本練習屬於課程
使用 PySpark 的機器學習
練習說明
- 建立一個物件,用來將文字切分成詞元。
- 建立一個物件,用來移除停用字。不要直接指定輸入欄位名稱,請改用前一個物件的
getOutputCol()方法。 - 建立物件以套用 hashing trick,並將資料轉換為 TF-IDF。再次使用
getOutputCol()方法。 - 建立一個 pipeline,將以上所有步驟包起來,並包含用來建立 Logistic Regression 模型的物件。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
from pyspark.ml.feature import Tokenizer, StopWordsRemover, HashingTF, IDF
# Break text into tokens at non-word characters
tokenizer = ____(inputCol='text', outputCol='words')
# Remove stop words
remover = ____(inputCol=____, outputCol='terms')
# Apply the hashing trick and transform to TF-IDF
hasher = ____(inputCol=____, outputCol="hash")
idf = ____(inputCol=____, outputCol="features")
# Create a logistic regression object and add everything to a pipeline
logistic = LogisticRegression()
pipeline = Pipeline(stages=[____, ____, ____, ____, logistic])