def features(x, d):
"""Design matrix whose columns are the powers x^0, x^1, ..., x^d."""
return x.reshape(-1, 1) ** np.arange(d + 1)
def fit_degree(x, y, d):
"""Least-squares weights of the degree-d polynomial fitted to (x, y)."""
return np.linalg.lstsq(features(x, d), y, rcond=None)[0]
def mse(w, x, y):
"""Mean squared error of the polynomial with weights w on (x, y)."""
return ((features(x, len(w) - 1) @ w - y) ** 2).mean()