95 KiB
95 KiB
In [1]:
import numpy as np
n = 100
bootstraps = 1000
predictions = np.random.rand(bootstraps, n) * 10 + 10
# The definition of targets has been updated, and was wrong earlier in the week.
targets = np.random.rand(1, n)
def calculate_key_metrics(y_pred, y_test):
y_pred = np.array(y_pred).T
y_test = np.array(y_test).T
error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )
return error, bias, variance
def print_key_metrics(predictions, targets):
mse, bias, variance = calculate_key_metrics(predictions, targets)
print(f"MSE ({mse:.3f}) = Bias ({bias:.3f}) + Variance ({variance:.3f}) = {bias + variance:.3f}")
print_key_metrics(predictions, targets)MSE (218.794) = Bias (210.484) + Variance (8.306) = 218.790
In [2]:
predictions = predictions * 0.5 + 20
print_key_metrics(predictions, targets)MSE (731.318) = Bias (729.240) + Variance (2.077) = 731.316
In [3]:
predictions = (predictions - np.mean(predictions, axis=0)) * 20
print_key_metrics(predictions, targets)MSE (830.999) = Bias (0.332) + Variance (830.621) = 830.954
In [4]:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import (
PolynomialFeatures,
) # use the fit_transform method of the created object!
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.utils import resampleIn [5]:
n = 40
bootstraps = 20
x = np.linspace(-3, 3, n)
y = np.exp(-(x**2)) + 1.5 * np.exp(-((x - 2) ** 2)) + np.random.normal(0, 0.1, size=n)
biases = []
variances = []
mses = []
p_degrees = list(range(1, 5))
for p in p_degrees:
predictions = np.zeros((bootstraps, int(n*0.2)), dtype=float)
targets = np.zeros((bootstraps, int(n*0.2)), dtype=float)
targets_nf = np.zeros((bootstraps, int(n*0.2)), dtype=float)
X = PolynomialFeatures(degree=p).fit_transform(x.reshape(-1, 1))
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)
for b in range(bootstraps):
x_sample, y_sample = resample(X_train, y_train)
model = LinearRegression().fit(X_train, y_train)
predictions[b, :] = model.predict(X_test)
targets[b, :] = y_test
#targets_nf[b, :] = y_test
mse, bias, variance = calculate_key_metrics(predictions, targets)
mses.append(mse)
biases.append(bias)
variances.append(variance)
plt.plot(p_degrees, np.array(mses), label="MSE", lw=3)
plt.plot(p_degrees, biases, label="Bias^2", linestyle="dashed", lw=2)
plt.plot(p_degrees, variances, label="Variance", linestyle="dashed", lw=2)
#plt.plot(range(1, 5), np.array(biases) + np.array(variances), label="Bias^2 + Variance", linestyle="dashed")
plt.xlabel("Model Complexity (Polynomial Degree)")
plt.ylabel("Error")
plt.legend()
plt.show()In [6]:
p = 3
biases = []
variances = []
mses = []
p_degrees = list(range(1, 5))
N_values = [10, 20, 40, 80, 160]
for N in N_values:
n = N
x = np.linspace(-3, 3, n)
X = PolynomialFeatures(degree=p).fit_transform(x.reshape(-1, 1))
y = np.exp(-(x**2)) + 1.5 * np.exp(-((x - 2) ** 2)) + np.random.normal(0, 0.1, size=n)
predictions = np.zeros((bootstraps, int(n*0.2)), dtype=float)
targets = np.zeros((bootstraps, int(n*0.2)), dtype=float)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)
for b in range(bootstraps):
x_sample, y_sample = resample(X_train, y_train)
model = LinearRegression().fit(X_train, y_train)
predictions[b, :] = model.predict(X_test)
targets[b, :] = y_test
mse, bias, variance = calculate_key_metrics(predictions, targets)
mses.append(mse)
biases.append(bias)
variances.append(variance)
plt.plot(N_values, np.array(mses), label="MSE", lw=3)
plt.plot(N_values, biases, label="Bias^2", linestyle="dashed", lw=2)
plt.plot(N_values, variances, label="Variance", linestyle="dashed", lw=2)
#plt.plot(range(1, 5), np.array(biases) + np.array(variances), label="Bias^2 + Variance", linestyle="dashed")
plt.xlabel("Training Data Size")
plt.ylabel("Error")
plt.legend()
plt.show()