將航班起飛機場做編碼
航班資料中的 org 欄位是類別變數,表示航班起飛的機場。
- ORD — O'Hare International Airport(芝加哥)
- SFO — San Francisco International Airport(舊金山)
- JFK — John F Kennedy International Airport(紐約)
- LGA — La Guardia Airport(紐約)
- SMF — Sacramento(沙加緬度)
- SJC — San Jose(聖荷西)
- OGG — Kahului(夏威夷)
當然這只是眾多機場中的一小部分。不過,因為這是類別變數,在用於迴歸模型之前需要做 one-hot 編碼。
資料已存在變數 flights 中。你已經用過字串索引器來建立一個欄位,將 org 中的字串對應到索引值。
你可以回顧位在 IPython Shell 旁「投影片(Slides)」面板中的課程投影片,這可能會有幫助。
本練習屬於課程
使用 PySpark 的機器學習
練習說明
- 匯入 one-hot 編碼器類別。
- 建立一個 one-hot 編碼器實例,將輸入欄位命名為
org_idx,輸出欄位命名為org_dummy。 - 對航班資料套用 one-hot 編碼器。
- 產生從類別值到二元編碼虛擬變數的對應摘要。只包含唯一值,並依
org_idx排序。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import the one hot encoder class
from pyspark.ml.____ import ____
# Create an instance of the one hot encoder
onehot = ____(inputCols=[____], outputCols=[____])
# Apply the one hot encoder to the flights data
onehot = onehot.____(____)
flights_onehot = onehot.____(____)
# Check the results
flights_onehot.____('org', 'org_idx', 'org_dummy').____().____('org_idx').show()