ฟังก์ชันสำหรับ pairs bootstrap
ตามที่ได้อธิบายไว้ในวิดีโอ pairs bootstrap คือการ resample คู่ของข้อมูล โดยนำแต่ละชุดของคู่ข้อมูลมาฟิตกับเส้นตรง ซึ่งในที่นี้ใช้ np.polyfit() กระบวนการนี้ทำซ้ำหลายครั้งเพื่อให้ได้ bootstrap replicate ของค่าพารามิเตอร์ เพื่อให้มีเครื่องมือที่ใช้งานได้จริง คุณจะเขียนฟังก์ชันสำหรับทำ pairs bootstrap กับชุดข้อมูล x,y
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Statistical Thinking in Python (ตอนที่ 2)
คำแนะนำการฝึกหัด
- กำหนดฟังก์ชันที่มี call signature เป็น
draw_bs_pairs_linreg(x, y, size=1)เพื่อประมาณค่าพารามิเตอร์ของ linear regression ด้วย pairs bootstrap- ใช้
np.arange()สร้างอาร์เรย์ของดัชนีตั้งแต่0ถึงlen(x)ซึ่งจะนำไปใช้ resample และเลือกค่าจากอาร์เรย์xและy - ใช้
np.empty()กำหนดค่าเริ่มต้นให้อาร์เรย์ replicate ของ slope และ intercept ให้มีขนาดเท่ากับsize - เขียน
forloop เพื่อ:- Resample ดัชนี
indsโดยใช้np.random.choice() - สร้างอาร์เรย์ \(x\) และ \(y\) ใหม่ชื่อ
bs_xและbs_yโดยใช้ดัชนีที่ resample แล้วbs_indsด้วยการ slicexและyด้วยbs_inds - ใช้
np.polyfit()กับอาร์เรย์ \(x\) และ \(y\) ใหม่ แล้วเก็บค่า slope และ intercept ที่คำนวณได้
- Resample ดัชนี
- คืนค่า pair bootstrap replicate ของ slope และ intercept
- ใช้
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
def draw_bs_pairs_linreg(x, y, size=1):
"""Perform pairs bootstrap for linear regression."""
# Set up array of indices to sample from: inds
inds = ____
# Initialize replicates: bs_slope_reps, bs_intercept_reps
bs_slope_reps = ____
bs_intercept_reps = ____
# Generate replicates
for i in range(size):
bs_inds = np.random.choice(____, size=____)
bs_x, bs_y = x[____], y[____]
bs_slope_reps[i], bs_intercept_reps[i] = ____
return bs_slope_reps, bs_intercept_reps