開始使用免費開始

梯度提升樹:預測

當你訓練好模型後,下一步就是用它來做預測。與 base R 使用 predict() 來產生預測不同,sparklyr 使用 ml_predict()ml_predict() 需要兩個引數:一個模型與一些測試資料。

ml_predict(a_model, testing_data)

常見的做法是把預測的應變數與實際的應變數做比較,並在 R 中繪圖呈現。準備這類資料的程式碼樣式如下。請注意,目前新增預測欄位必須在本機端完成,因此你需要先收集結果。

predicted_vs_actual <- testing_data %>%
  select(actual) %>%
  collect() %>%
  mutate(predicted)

本練習屬於課程

使用 R 的 sparklyr:Spark 入門

檢視課程

練習說明

已為你建立名為 spark_conn 的 Spark 連線。連到 Spark 中之訓練與測試資料集的 tibbles 已預先定義為 track_data_to_model_tbltrack_data_to_predict_tbl。梯度提升樹模型已預先定義為 gradient_boosted_trees_model

  • 定義變數 predicted,其中包含我們測試資料的模型預測值。
    • 以模型與測試資料作為引數呼叫 ml_predict()。此函式會為測試資料集產生預測,並新增名為 prediction 的新欄位。
    • 使用 pull() 擷取此欄位,並指定給 predicted
  • 定義變數 responses,以便準備比較預測與實際應變數所需的資料:
    • 選取應變數欄位 year
    • 收集結果。
    • 使用 mutate()predicted 中產生的預測加入。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Training, testing sets & model are pre-defined
track_data_to_model_tbl
track_data_to_predict_tbl
gradient_boosted_trees_model

# Predict the responses for the testing data
predicted <- ___(
      ___,
      ___) %>% pull(prediction)

# Prepare the data for comparing predicted responses with actual responses
responses <- track_data_to_predict_tbl %>%
  # Select the response column
  ___ %>%
  # Collect the results
  ___ %>%
  # Add in the predictions
  mutate(___)
編輯並執行程式碼