เปอร์เซ็นไทล์และ partial function
ในแบบฝึกหัดนี้ จะได้ฝึกกำหนด argument ของฟังก์ชันไว้ล่วงหน้า เพื่อให้สามารถตั้งค่าการทำงานของฟังก์ชันก่อนเรียกใช้จริงได้ โดยจะนำเทคนิคนี้มาคำนวณค่าเปอร์เซ็นไทล์หลายระดับจากข้อมูล โดยใช้ฟังก์ชัน percentile() ใน numpy ฟังก์ชันเดียวกัน
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Machine Learning สำหรับข้อมูล Time Series ใน Python
คำแนะนำการฝึกหัด
- Import
partialจากfunctools - ใช้ฟังก์ชัน
partial()สร้าง feature generator หลายตัวสำหรับคำนวณค่าเปอร์เซ็นไทล์ของข้อมูล โดยใช้ list comprehension - นำ rolling window (
prices_perc_rolling) ที่เตรียมไว้ให้มาคำนวณค่า quantile โดยใช้percentile_functions - แสดงผลลัพธ์ด้วยโค้ดที่เตรียมไว้ให้
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Import partial from functools
____
percentiles = [1, 10, 25, 50, 75, 90, 99]
# Use a list comprehension to create a partial function for each quantile
percentile_functions = [____(np.percentile, q=percentile) for percentile in percentiles]
# Calculate each of these quantiles on the data using a rolling window
prices_perc_rolling = prices_perc.rolling(20, min_periods=5, closed='right')
features_percentiles = prices_perc_rolling.____(____)
# Plot a subset of the result
ax = features_percentiles.loc[:"2011-01"].plot(cmap=plt.cm.viridis)
ax.legend(percentiles, loc=(1.01, .5))
plt.show()