aNet.ai
Data Science/Lab work
0day streak0XP · Lv 1
← Lab 6 overview and setup
Lab 6 · Section 3 of 7

Calculate correlation by hand

Task 3 · steps 1–3

First · connect to the lecture

Pearson's r from the Week 5 lecture is computed from deviations, products and squared deviations before any code runs.

Lab 6 PDF p. 3 · Task 3 (first part)

Your task

For x = [1, 2, 3, 4] and y = [1, 3, 2, 4], find both means, complete the deviation table, substitute into the formula, then verify with NumPy.

Evidence to include

Means 2.5 and 2.5; sums 4, 5 and 5; r = 4/√25 = 0.8; deviation totals of zero; matching code output.

Worked example and code

Try the task in the PDF first, then compare your working below. Run the code in your own Python notebook.

Open Lab 6 instructions (PDF)

Task 3 · L6 p. 3. Do the table on paper before running anything.

x mean = (1+2+3+4)/4 = 2.5; y mean = (1+3+2+4)/4 = 2.5.

x y dx dy dx × dy dx² dy²
1 1 −1.5 −1.5 2.25 2.25 2.25
2 3 −0.5 0.5 −0.25 0.25 0.25
3 2 0.5 −0.5 −0.25 0.25 0.25
4 4 1.5 1.5 2.25 2.25 2.25
Sum 0 0 4 5 5

Both deviation totals are 0, as they must be. Substituting into Pearson's formula:

r = 4 / √(5 × 5) = 4 / 5 = 0.8

Interpretation: r is positive, so larger x tends to go with larger y. It is not 1 because the points are not on one straight line: the middle pair (2,3) and (3,2) runs against the trend, contributing −0.25 each.

x_hand = np.array([1, 2, 3, 4], dtype=float)
y_hand = np.array([1, 3, 2, 4], dtype=float)
dx = x_hand - x_hand.mean()
dy = y_hand - y_hand.mean()
numerator = np.sum(dx * dy)
denominator = np.sqrt(np.sum(dx ** 2) * np.sum(dy ** 2))
print("Formula result:", numerator / denominator)
print("NumPy check:", np.corrcoef(x_hand, y_hand)[0, 1])

Output: both lines print 0.8 (possibly 0.7999999999999999, a floating-point rounding difference). If your hand result differs, check that x and y stay paired row by row, then the means, the signs of the deviations and the three sums.

Saved only in this browser. This note doesn’t fill in the downloaded notebook; “reviewed” is a personal checklist, not a grade.

aNet.ai · Data Science Fundamentals · Weeks 1–6 · practice material, not an official examProgress saved in this browser