開始使用免費開始

Gradient boosted trees:建模

梯度提升(gradient boosting)是一種用來提升其他模型效能的技術。概念是先訓練一個較弱但計算容易的模型,接著把反應變數換成該模型的殘差,再去擬合另一個模型。將原本預測反應的模型與這個預測殘差的新模型「相加」,你就會得到更準確的模型。你可以重複這個流程,一次又一次地為先前模型的殘差建立新模型,並把結果加總起來。每次迭代後,模型都會變得越來越強。

以更具體的例子來說,sparklyr 使用的是梯度提升樹(gradient boosted trees),也就是以決策樹作為「弱但易算」的基礎模型來進行梯度提升。這種方法可用於分類問題(反應變數為類別)與回歸問題(反應變數為連續)。在你將要使用的回歸情境中,用來衡量點位擬合得多差的指標就是殘差。

關於決策樹的更深入介紹,請參考課程[Supervised Learning in R: Classification](https://www.datacamp.com/courses/supervised-learning-in-r-classification)與[Supervised Learning in R: Regression](https://www.datacamp.com/courses/supervised-learning-in-r-regression)。後者也涵蓋了梯度提升。

若要在 sparklyr 中執行梯度提升樹模型,請呼叫 ml_gradient_boosted_trees()。本章第一個練習已經討論過此函式的用法。

本練習屬於課程

使用 R 的 sparklyr:Spark 入門

檢視課程

練習說明

已為你建立名為 spark_conn 的 Spark 連線。結合並過濾後、儲存在 Spark 中的曲目中繼資料/timbre 資料,已預先連結為名為 track_data_to_model_tbl 的 tibble。

  • 取得包含字串 "timbre" 的欄位,做為特徵使用。
    • 使用 colnames() 取得 track_data_to_model_tbl 的欄位名稱。注意,names() 不會得到你要的結果。
    • 使用 str_subset() 篩選欄位。
    • 該函式的 pattern 引數應為 fixed("timbre")
    • 將結果指派給 feature_colnames
  • 使用 reformulate() 建立模型的 formula
    • termlabels 引數(公式的輸入)應為 feature_colnames
    • response 引數(公式的輸出)應為 "year"
    • 將結果指派給 year_formula
    • 如此使用 reformulate() 會把 feature_colnames 中的所有變數以 + 連接,形成 formula 的右手邊。這會得到公式 year ~ timbre1 + timbre2 + ... + timbre12,用來定義要納入模型的變數關係。
  • 執行梯度提升模型。
    • 呼叫 ml_gradient_boosted_trees(),並以你建立的 year_formula 作為唯一引數。
    • 將結果指派給 gradient_boosted_trees_model

動手互動練習

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

# track_data_to_model_tbl has been pre-defined
track_data_to_model_tbl

feature_colnames <- track_data_to_model_tbl %>%
  # Get the column names
  ___ %>%
  # Limit to the timbre columns
  ___(___(___))

feature_colnames

# Create the formula for the model
year_formula <- ___

gradient_boosted_trees_model <- track_data_to_model_tbl %>%
  # Run the gradient boosted trees model
  ___
編輯並執行程式碼