使用視覺化:distplot
了解應變數的分佈非常重要,會影響你選擇的模型或前處理方式。最好的方法之一是把分佈畫出來;不過在 PySpark 中沒有內建繪圖功能,因此你需要先做一些中介步驟,才能正確繪製。本練習中你會視覺化變數 'LISTPRICE',並透過計算偏態(skewness)來更深入了解其分佈。
matplotlib.pyplot 與 seaborn 套件已分別以別名 plt 與 sns 匯入供你使用。
本練習屬於課程
使用 PySpark 進行特徵工程
練習說明
- 使用
sample()對資料框df抽樣 50%,確保不放回抽樣,並將亂數種子設為 42。 - 使用
toPandas()將 Spark DataFrame 轉換為pandas.DataFrame()。 - 使用
seaborn的distplot()方法繪製分佈圖。 - 從
pyspark.sql.functions匯入skewness()函式,並用agg()對'LISTPRICE'欄位做聚合來計算偏態。記得使用collect()取得結果以完成運算評估。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Select a single column and sample and convert to pandas
sample_df = df.select(['LISTPRICE']).____(____, ____, 42)
pandas_df = sample_df.____()
# Plot distribution of pandas_df and display plot
sns.____(____)
plt.show()
# Import skewness function
from pyspark.sql.functions import skewness
# Compute and print skewness of LISTPRICE
print(df.____({____: ____}).collect())