13/25
Part 3 of 5 · UnbiasedLearn and do

Divide θ's top and bottom by the same count, or by none

The second detail is the divisor inside θ. theta_numpy is this step's task.

import statistics

x = np.array([2.0, 4, 6, 8, 4, 6, 8, 10])
y = np.array([2.0, 4, 5, 7, 6, 8, 7, 9])
c = np.cov(x, y)
print(theta_numpy(y, x))
print(statistics.linear_regression(x, y).slope)
print(c[0, 1] / np.var(x))
0.75
0.75
0.8571428571428571

Three ways to compute θ\theta on the eight users. The first two give the slope, 0.75. The third comes out 0.857, which is 8/78/7 times too big. np.cov(x, y) returns a 2 by 2 grid: the variance of x at [0, 0] and the covariance at [0, 1].

The reason is the divisor. θ\theta is a ratio of two averages over the same users. Write Sxy=∑i(xi−xˉ)(yi−yˉ)S_{xy} = \sum_i (x_i - \bar{x})(y_i - \bar{y}) for the sum of products and Sxx=∑i(xi−xˉ)2S_{xx} = \sum_i (x_i - \bar{x})^2 for the sum of squares. Divide both by the same count and the count cancels:

θ=Sxy/(n−d)Sxx/(n−d)=SxySxx\theta = \frac{S_{xy} / (n - d)}{S_{xx} / (n - d)} = \frac{S_{xy}}{S_{xx}}

Here dd is the ddof, short for delta degrees of freedom: the number taken off nn in the divisor, 0 or 1. Use different ones on top and bottom and the count doesn't cancel. The defaults make that easy to do by accident:

CallDivides by
np.cov(x, y)n−1n - 1
np.var(x)nn
statistics.covariance(x, y)n−1n - 1
statistics.variance(x)n−1n - 1
statistics.pvariance(x)nn

The safest version never divides by a count at all: a sum of products over a sum of squares, as cuped does. On the practice data, that, np.cov for both, and statistics.linear_regression(x, y).slope all match np.polyfit(x, y, 1)[0] to within 10−1510^{-15}. The names aren't the point. Any one convention, used on both sides, works.

In the editor, write theta_numpy(y, x) with np.cov for both numbers.