42 KiB
42 KiB
In [8]:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScalerIn [28]:
n = 100
x = np.linspace(-3, 3, n)
y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(n)In [29]:
def polynomial_features(x, p, intercept=False):
n = len(x)
X = np.zeros((n, p + 1))
#X[:, 0] = ...
#X[:, 1] = ...
#X[:, 2] = ...
# could this be a loop?In [41]:
def polynomial_features(x, p, intercept=False):
n = len(x)
X = np.zeros((n, p))
X[:, 0] = x[:]
X[:, 1] = x**2
X[:, 2] = x**3
return XIn [42]:
X = polynomial_features(x, 3)In [78]:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
x_train = X_train[:, 0] # These are used for plotting
x_test = X_test[:, 0] # These are used for plottingIn [79]:
scaler = StandardScaler()
scaler.fit(X_train)
X_train_s = scaler.transform(X_train)
X_test_s = scaler.transform(X_test)
y_offset = np.mean(y_train)In [80]:
def Ridge_parameters(X, y):
# Assumes X is scaled and has no intercept column
return np.linalg.inv(X.T @ X) @ X.T @ y
beta = Ridge_parameters(X_train_s, y_train)In [82]:
plt.plot(x, y)
plt.scatter(x_train, X_train_s @ beta + y_offset)
plt.scatter(x_test, X_test_s @ beta + y_offset)Out [82]:
<matplotlib.collections.PathCollection at 0x113e21950>