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 on the eight users. The first two give the slope, 0.75. The third comes out 0.857, which is 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. is a ratio of two averages over the same users. Write for the sum of products and for the sum of squares. Divide both by the same count and the count cancels:
Here is the ddof, short for delta degrees of freedom: the number taken off 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:
| Call | Divides by |
|---|---|
np.cov(x, y) | |
np.var(x) | |
statistics.covariance(x, y) | |
statistics.variance(x) | |
statistics.pvariance(x) |
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 . 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.