計算變異數
了解常用函式在底層做了什麼很重要。即使你可能已經會計算變異數,本課屬於入門課程,並不預設這些知識。在這個練習中,我們會依照影片中說明的公式,明確計算「鳶尾花(Iris veriscolor)」花瓣長度的變異數。接著,我們會用 np.var() 來計算一次作為對照。
本練習屬於課程
Statistical Thinking in Python (Part 1)
練習說明
- 建立一個名為
differences的陣列,內容為花瓣長度(versicolor_petal_length)減去其平均花瓣長度的差值。變數versicolor_petal_length已經以 NumPy 陣列形式存在工作空間,因此你可以直接利用 NumPy 的向量化運算。 - 將此陣列中每個元素平方。例如,
x**2會將陣列x的每個元素平方。把結果存為diff_sq。 - 使用
np.mean()計算diff_sq中各元素的平均值。把結果存為variance_explicit。 - 使用
np.var()計算versicolor_petal_length的變異數。把結果存為variance_np。 - 在一次
print呼叫中同時印出variance_explicit和variance_np,以確認兩者一致。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Array of differences to mean: differences
# Square the differences: diff_sq
# Compute the mean square difference: variance_explicit
# Compute the variance using NumPy: variance_np
# Print the results