Logistic Regression 模型訓練
在為資料建立標籤與特徵之後,我們已經準備好訓練可以從資料中學習的模型了。不過在訓練之前,在本練習的最後一部分,你會先把資料分成訓練集與測試集,對訓練集執行 Logistic Regression 模型,最後檢查在訓練資料上訓練出的模型之準確度。
請記得,你的工作環境中已提供 SparkContext sc,以及變數 samples。
本練習屬於課程
使用 PySpark 的 Big Data 基礎
練習說明
- 以 80:20 的比例將合併後的資料切分為訓練集與測試集。
- 使用訓練集訓練 Logistic Regression 模型。
- 以已訓練的模型對測試集產生預測標籤。
- 使用
zip函式將測試集中的標籤與預測結果的標籤配對。 - 使用原始與預測標籤計算模型的準確度,並將結果印出。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Split the data into training and testing
train_samples,test_samples = samples.____([0.8, 0.2])
# Train the model
model = LogisticRegressionWithLBFGS.train(____)
# Create a prediction label from the test data
predictions = model.____(test_samples.map(lambda x: x.features))
# Combine original labels with the predicted labels
labels_and_preds = test_samples.map(lambda x: x.label).zip(____)
# Check the accuracy of the model on the test data
accuracy = labels_and_preds.filter(lambda x: x[0] == x[____]).count() / float(test_samples.count())
print("Model accuracy : {:.2f}".format(____))