'█' * k repeats the block k times, 8 blocks per unit of variance. θ=0 is no adjustment at all.
That U holds for any data. Write σX2 and σY2 for the variances of X and Y, and σXY for their covariance: the average, over users, of the product of their two distances from the means. Subtracting the constant θXˉ doesn't change a variance, so set it aside. What's left is
Var(Y−θX)=σY2−2θσXY+θ2σX2In words: a parabola in θ that opens upward. Its lowest point is at
θ∗=σX2σXY=Var(X)Cov(X,Y)the covariance over the variance of X. The star marks the best θ.
θ∗ is a number you already know. It's the least-squares slope of Y on X, the line in the scatter. On real data you don't know the true covariance and variance, so you estimate θ from the users in the test: their covariance over their variance of x, which is the fitted slope.
def cuped(y, x):
xc = x - x.mean()
theta = float((xc * (y - y.mean())).sum() / (xc * xc).sum())
return y - theta * xc, theta
y_cv, theta = cuped(y, x)
print(theta, np.polyfit(x, y, 1)[0])
0.75 0.75
That's the whole practice problem in three lines. np.polyfit(x, y, 1)[0] is the slope of the least-squares line, as a check, and it agrees.
Read the theta line inside out. xc * (y - y.mean()) multiplies each user's two distances from the means, and .sum() adds them up. The bottom does the same with xc against itself. That's the covariance over the variance with the count left off both, since it would cancel. float makes the result a plain Python number.
In the editor, write lowest_theta(y, x, thetas): the bottom of the U, found by trying each value.