Example: Regression with estimated measurement noise#
Let’s reuse our synthetic dataset:
where \(\epsilon_i \sim N(0,1)\) and where we sample \(x_i \sim U([0,1])\). Here is how to generate this synthetic dataset and how it looks like:
We will be fitting polynomials, so let’s copy-paste the code we developed for computing the design matrix:
In the previous section, we saw that when least squares are interpreted probabilistically the weight estimate does not change. So, we can obtain it just like before:
# The degree of the polynomial
degree = 2
# The design matrix
Phi = get_polynomial_design_matrix(x[:, None], degree)
# Solve the least squares problem
w, sum_res, _, _ = np.linalg.lstsq(Phi, y, rcond=None)
Notice that we have now also stored the second output of numpy.linalg.lstsq
. This is the sum of the residuals, i.e., it is:
Let’s test this just to be sure…
print(f'sum_res = {sum_res[0]:1.4f}')
print(f'compare to = {np.linalg.norm(y-np.dot(Phi, w)) ** 2:1.4f}')
sum_res = 0.0749
compare to = 0.0749
It looks correct. We saw that the sum of residuals gives us the maximum likelihood estimate of the noise variance through this formula:
Let’s compute it:
sigma2_MLE = sum_res[0] / num_obs
sigma_MLE = np.sqrt(sigma2_MLE)
print(f'True sigma = {sigma_true:1.4f}')
print(f'MLE sigma = {sigma_MLE:1.4f}')
True sigma = 0.1000
MLE sigma = 0.0865
Let’s also visualize this noise. The prediction at each \(x\) is Gaussian with mean \(\mathbf{w}^T\boldsymbol{\phi}(x)\) and variance \(\sigma_{\text{MLE}}^2\). So, we can simply create a 95% credible interval by subtracting and adding (about) two \(\sigma_{\text{MLE}}\) to the mean.
fig, ax = make_full_width_fig()
# Some points on which to evaluate the regression function
xx = np.linspace(-1, 1, 100)
# The true connection between x and y
yy_true = w0_true + w1_true * xx + w2_true * xx ** 2
# The mean prediction of the model we just fitted
Phi_xx = get_polynomial_design_matrix(xx[:, None], degree)
yy = np.dot(Phi_xx, w)
# Lower bound for 95% credible interval
sigma_MLE = np.sqrt(sigma2_MLE)
yy_l = yy - 2.0 * sigma_MLE
# Upper bound for 95% credible interval
yy_u = yy + 2.0 * sigma_MLE
# plot mean prediction
ax.plot(xx, yy, '--', label='Mean prediction')
# plot shaded area for 95% credible interval
ax.fill_between(xx, yy_l, yy_u, alpha=0.25, label='95% credible interval')
# plot the data again
ax.plot(x, y, 'kx', label='Observed data')
# overlay the true
ax.plot(xx, yy_true, label='True response surface')
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
plt.legend(loc='best')
save_for_book(fig, 'ch15.fig21')
Questions#
Increase the number of observations
num_obs
and notice that the likelihood noise converges to the true measurement noise.Change the polynomial degree to one so that you just fit a line. What does the model think about the noise now?