Path: blob/master/deprecated/scripts/biasVarModelComplexity3.py
1192 views
import superimport12import matplotlib.pyplot as plt3import numpy as np4from numpy.linalg import cholesky5from numpy import linalg678def gaussSample(mu, sigma, n):9A = cholesky(sigma)10Z = np.random.normal(loc=0, scale=1, size=(len(mu), n))11return np.dot(A, Z).T + mu121314def ridge(X, y, lam):15"""16This function can be completed pinv as well17"""18W = np.dot(linalg.pinv((np.dot(X.T, X) + np.sqrt(lam) * np.eye(X.shape[0]))), np.dot(X.T, y))19return W202122def basisExpansion(X, s=None, centers=[]):23n = 2524if not s:25s = np.std(X) / np.sqrt(n)2627if not len(centers):28centers = X[1:]2930Xbasis = np.ones((X.shape[0], n))31for i in range(1, n):32Xbasis[:, i] = np.ravel(np.exp((-1 / (2 * s ** 2)) * (X - centers[i - 1]) ** 2))33return Xbasis, s, centers343536def fun(X):37"""38Cosine function39"""40return np.cos(2 * np.pi * X)414243def synthesizeData(n, d):44sigma = np.array([[0.1]])45mu = np.array([0])46X = np.random.rand(n, d)47y = fun(X) + gaussSample(mu, sigma, n)48return X, y495051n = 2552d = 153lambdas = [np.exp(5), np.exp(-5)]54ndataSets = 10055showNsets = 2056np.random.seed(42)5758domain = np.arange(0, 1, 0.0005)59fs = 166061nr = 262nc = 26364fig, ax = plt.subplots(2, 2, figsize=(12, 9))65for lam in range(len(lambdas)):66yhat = np.zeros((len(domain), ndataSets))67for j in range(ndataSets):68X, y = synthesizeData(n, d)69X, s, centers = basisExpansion(X)70W = ridge(X, y, lambdas[lam])71yhat[:, j] = np.ravel(np.dot(basisExpansion(domain, s, centers)[0], W))7273ax[lam, 0].plot(domain[..., np.newaxis].repeat(20, axis=1), yhat[:, :showNsets], color='#ff7f00')74ax[lam, 0].set_xlim([-0.1, 1.1])75ax[lam, 0].set_ylim([-1.5, 1.5])76ax[lam, 0].set_title('ln($\lambda$) = {}'.format(np.log(lambdas[lam])))7778ax[lam, 1].plot(domain, fun(domain), lineWidth=2.5)79ax[lam, 1].plot(domain, np.mean(yhat, axis=1), linestyle=':', lineWidth=2.5)80ax[lam, 1].set_title('ln($\lambda$) = {}'.format(np.log(lambdas[lam])))8182fig.savefig('../figures/biasVarModelComplexityV3.png')838485