處理離群值
在這個練習中,你要處理離群值——也就是與其他資料點差異極大的資料點,因此需要用不同於「看起來正常」的資料點的方式來處理。你會使用前一個練習的輸出(隨時間的百分比變化)來偵測離群值。首先,你會撰寫一個函式,將離群的資料點替換為整個時間序列的中位數。
本練習屬於課程
Python 的時間序列資料機器學習
練習說明
- 定義一個函式,接受一個輸入的 series,並執行以下操作:
- 計算每個資料點與該 series 平均值之距離的絕對值,然後為那些距離超過平均值 3 倍標準差的資料點建立布林遮罩(boolean mask)。
- 使用這個布林遮罩,將離群值替換為整個 series 的中位數。
- 將此函式套用到你的資料,並使用提供的程式碼視覺化結果。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
def replace_outliers(series):
# Calculate the absolute difference of each timepoint from the series mean
absolute_differences_from_mean = np.abs(series - np.mean(series))
# Calculate a mask for the differences that are > 3 standard deviations from zero
this_mask = absolute_differences_from_mean > (np.____(series) * ____)
# Replace these values with the median accross the data
series[this_mask] = np.____(series)
return series
# Apply your preprocessing function to the timeseries and plot the results
prices_perc = prices_perc.____
prices_perc.loc["2014":"2015"].plot()
plt.show()