開始使用免費開始

以簡單方式處理遺漏值與類別值

隨機森林迴歸相當穩健,讓我們可以略過許多耗時又繁瑣的資料前處理步驟。雖然有些隨機森林的實作會自動處理遺漏值與類別值,但 PySpark 的並不會。不過其背後數學相同,因此我們可以用一些直覺式(naive)的值替換來因應。

對於遺漏值,由於資料都是嚴格正值,我們將指定為 -1。隨機森林會在此值上進行分割,並把它與同一個特徵中的其他值區別對待。

對於類別值,我們可以把文字值對應成數字,隨機森林同樣會透過在這些值上分割來妥善處理。在這個範例中,會重溫 Introduction to PySpark 的 pipelines,讓程式碼更精簡。請注意,練習一開始會先顯示資料框欄位的 dtypes,請在本練習結束時將其與結果比較。

注意:PipelineStringIndexer 已替你匯入。清單 categorical_cols 也已可用。

本練習屬於課程

使用 PySpark 進行特徵工程

檢視課程

練習說明

  • 使用 fillna()subset 參數,將 WALKSCOREBIKESCORE 的值替換為 -1。
  • 使用清單生成式,針對 categorical_cols 中的每個欄位建立一個 StringIndexer 的清單。
  • 對管線 indexer_pipeline 套用 fit()transform()
  • 使用 drop() 移除 categorical_cols,因為已經不需要它們。使用 dtypes 檢視結果的資料型別。

動手互動練習

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

# Replace missing values
df = df.____(____, ____=[____, ____])

# Create list of StringIndexers using list comprehension
indexers = [____(inputCol=____, outputCol=____+"_IDX")\
            .setHandleInvalid("keep") for ____ in ____]
# Create pipeline of indexers
indexer_pipeline = Pipeline(stages=indexers)
# Fit and Transform the pipeline to the original data
df_indexed = ____.____(df).____(df)

# Clean up redundant columns
df_indexed = df_indexed.____(*____)
# Inspect data transformations
print(df_indexed.dtypes)
編輯並執行程式碼