305 KiB
305 KiB
In [1]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.preprocessing import PolynomialFeatures
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.utils import resample
np.random.seed(2018)
n = 40
n_boostraps = 100
maxdegree = 14
# Make data set.
x = np.linspace(-3, 3, n).reshape(-1, 1)
y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
error = np.zeros(maxdegree)
bias = np.zeros(maxdegree)
variance = np.zeros(maxdegree)
polydegree = np.zeros(maxdegree)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
for degree in range(maxdegree):
model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
y_pred = np.empty((y_test.shape[0], n_boostraps))
for i in range(n_boostraps):
x_, y_ = resample(x_train, y_train)
y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
polydegree[degree] = degree
error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
print('Polynomial degree:', degree)
print('Error:', error[degree])
print('Bias^2:', bias[degree])
print('Var:', variance[degree])
print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
plt.plot(polydegree, error, label='Error')
plt.plot(polydegree, bias, label='bias')
plt.plot(polydegree, variance, label='Variance')
plt.legend()
plt.show()Polynomial degree: 0 Error: 0.32149601703519115 Bias^2: 0.3123314713548606 Var: 0.009164545680330616 0.32149601703519115 >= 0.3123314713548606 + 0.009164545680330616 = 0.3214960170351912 Polynomial degree: 1 Error: 0.08426840630693412 Bias^2: 0.0796891867672603 Var: 0.004579219539673834 0.08426840630693412 >= 0.0796891867672603 + 0.004579219539673834 = 0.08426840630693413 Polynomial degree: 2 Error: 0.10398646080125037 Bias^2: 0.10077114273548984 Var: 0.0032153180657605116 0.10398646080125037 >= 0.10077114273548984 + 0.0032153180657605116 = 0.10398646080125036 Polynomial degree: 3 Error: 0.06547790180152352 Bias^2: 0.062082386342319454 Var: 0.0033955154592040923 0.06547790180152352 >= 0.062082386342319454 + 0.0033955154592040923 = 0.06547790180152355 Polynomial degree: 4 Error: 0.06844519414009445 Bias^2: 0.06453579006728322 Var: 0.003909404072811221 0.06844519414009445 >= 0.06453579006728322 + 0.003909404072811221 = 0.06844519414009444 Polynomial degree: 5 Error: 0.05227921801205679 Bias^2: 0.04818727730430286 Var: 0.004091940707753925 0.05227921801205679 >= 0.04818727730430286 + 0.004091940707753925 = 0.05227921801205679 Polynomial degree: 6 Error: 0.03781367141738902 Bias^2: 0.03365768507152769 Var: 0.0041559863458613296 0.03781367141738902 >= 0.03365768507152769 + 0.0041559863458613296 = 0.03781367141738902 Polynomial degree: 7 Error: 0.027609773491022394 Bias^2: 0.022999498260366198 Var: 0.004610275230656182 0.027609773491022394 >= 0.022999498260366198 + 0.004610275230656182 = 0.02760977349102238 Polynomial degree: 8 Error: 0.017355848195593312 Bias^2: 0.010331721306655165 Var: 0.007024126888938144 0.017355848195593312 >= 0.010331721306655165 + 0.007024126888938144 = 0.01735584819559331 Polynomial degree: 9 Error: 0.026605727637184558 Bias^2: 0.010018312644139219 Var: 0.016587414993045335 0.026605727637184558 >= 0.010018312644139219 + 0.016587414993045335 = 0.026605727637184554 Polynomial degree: 10 Error: 0.021592704588021178 Bias^2: 0.010516485576646504 Var: 0.01107621901137467 0.021592704588021178 >= 0.010516485576646504 + 0.01107621901137467 = 0.021592704588021174 Polynomial degree: 11 Error: 0.07160048164232538 Bias^2: 0.014436800088896381 Var: 0.05716368155342902 0.07160048164232538 >= 0.014436800088896381 + 0.05716368155342902 = 0.0716004816423254 Polynomial degree: 12 Error: 0.11547777218876518 Bias^2: 0.016285782696017142 Var: 0.09919198949274803 0.11547777218876518 >= 0.016285782696017142 + 0.09919198949274803 = 0.11547777218876518 Polynomial degree: 13 Error: 0.2284246870217162 Bias^2: 0.01975416527168255 Var: 0.20867052175003364 0.2284246870217162 >= 0.01975416527168255 + 0.20867052175003364 = 0.2284246870217162
In [3]:
#print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
def true_fun(X):
return np.cos(1.5 * np.pi * X)
np.random.seed(0)
n_samples = 100
degrees = [1, 4, 15]
X = np.sort(np.random.rand(n_samples))
y = true_fun(X) + np.random.randn(n_samples) * 0.1
plt.figure(figsize=(14, 5))
for i in range(len(degrees)):
ax = plt.subplot(1, len(degrees), i + 1)
plt.setp(ax, xticks=(), yticks=())
polynomial_features = PolynomialFeatures(degree=degrees[i],
include_bias=False)
linear_regression = LinearRegression()
pipeline = Pipeline([("polynomial_features", polynomial_features),
("linear_regression", linear_regression)])
pipeline.fit(X[:, np.newaxis], y)
# Evaluate the models using crossvalidation
scores = cross_val_score(pipeline, X[:, np.newaxis], y,
scoring="neg_mean_squared_error", cv=10)
X_test = np.linspace(0, 1, 100)
plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model")
plt.plot(X_test, true_fun(X_test), label="True function")
plt.scatter(X, y, edgecolor='b', s=20, label="Samples")
plt.xlabel("x")
plt.ylabel("y")
plt.xlim((0, 1))
plt.ylim((-2, 2))
plt.legend(loc="best")
plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format(
degrees[i], -scores.mean(), scores.std()))
plt.show()In [6]:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import KFold
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import PolynomialFeatures
# A seed just to ensure that the random numbers are the same for every run.
# Useful for eventual debugging.
np.random.seed(3155)
# Generate the data.
nsamples = 1000
x = np.random.randn(nsamples)
y = 3*x**2 + np.random.randn(nsamples)
## Cross-validation on Ridge regression using KFold only
# Decide degree on polynomial to fit
poly = PolynomialFeatures(degree = 6)
# Decide which values of lambda to use
nlambdas = 500
lambdas = np.logspace(-3, 5, nlambdas)
# Initialize a KFold instance
k = 5
kfold = KFold(n_splits = k)
# Perform the cross-validation to estimate MSE
scores_KFold = np.zeros((nlambdas, k))
i = 0
for lmb in lambdas:
ridge = Ridge(alpha = lmb)
j = 0
for train_inds, test_inds in kfold.split(x):
xtrain = x[train_inds]
ytrain = y[train_inds]
xtest = x[test_inds]
ytest = y[test_inds]
Xtrain = poly.fit_transform(xtrain[:, np.newaxis])
ridge.fit(Xtrain, ytrain[:, np.newaxis])
Xtest = poly.fit_transform(xtest[:, np.newaxis])
ypred = ridge.predict(Xtest)
scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)
j += 1
i += 1
estimated_mse_KFold = np.mean(scores_KFold, axis = 1)
## Cross-validation using cross_val_score from sklearn along with KFold
# kfold is an instance initialized above as:
# kfold = KFold(n_splits = k)
estimated_mse_sklearn = np.zeros(nlambdas)
i = 0
for lmb in lambdas:
ridge = Ridge(alpha = lmb)
X = poly.fit_transform(x[:, np.newaxis])
estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)
# cross_val_score return an array containing the estimated negative mse for every fold.
# we have to the the mean of every array in order to get an estimate of the mse of the model
estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
i += 1
## Plot and compare the slightly different ways to perform cross-validation
plt.figure()
plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
#plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')
plt.xlabel('log10(lambda)')
plt.ylabel('mse')
plt.legend()
plt.show()In [7]:
# Common imports
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.model_selection import train_test_split
from sklearn.utils import resample
from sklearn.metrics import mean_squared_error
# Where to save the figures and data files
PROJECT_ROOT_DIR = "Results"
FIGURE_ID = "Results/FigureFiles"
DATA_ID = "DataFiles/"
if not os.path.exists(PROJECT_ROOT_DIR):
os.mkdir(PROJECT_ROOT_DIR)
if not os.path.exists(FIGURE_ID):
os.makedirs(FIGURE_ID)
if not os.path.exists(DATA_ID):
os.makedirs(DATA_ID)
def image_path(fig_id):
return os.path.join(FIGURE_ID, fig_id)
def data_path(dat_id):
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
plt.savefig(image_path(fig_id) + ".png", format='png')
infile = open(data_path("EoS.csv"),'r')
# Read the EoS data as csv file and organize the data into two arrays with density and energies
EoS = pd.read_csv(infile, names=('Density', 'Energy'))
EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
EoS = EoS.dropna()
Energies = EoS['Energy']
Density = EoS['Density']
# The design matrix now as function of various polytrops
Maxpolydegree = 30
X = np.zeros((len(Density),Maxpolydegree))
X[:,0] = 1.0
testerror = np.zeros(Maxpolydegree)
trainingerror = np.zeros(Maxpolydegree)
polynomial = np.zeros(Maxpolydegree)
trials = 100
for polydegree in range(1, Maxpolydegree):
polynomial[polydegree] = polydegree
for degree in range(polydegree):
X[:,degree] = Density**(degree/3.0)
# loop over trials in order to estimate the expectation value of the MSE
testerror[polydegree] = 0.0
trainingerror[polydegree] = 0.0
for samples in range(trials):
x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)
model = LinearRegression(fit_intercept=False).fit(x_train, y_train)
ypred = model.predict(x_train)
ytilde = model.predict(x_test)
testerror[polydegree] += mean_squared_error(y_test, ytilde)
trainingerror[polydegree] += mean_squared_error(y_train, ypred)
testerror[polydegree] /= trials
trainingerror[polydegree] /= trials
print("Degree of polynomial: %3d"% polynomial[polydegree])
print("Mean squared error on training data: %.8f" % trainingerror[polydegree])
print("Mean squared error on test data: %.8f" % testerror[polydegree])
plt.plot(polynomial, np.log10(trainingerror), label='Training Error')
plt.plot(polynomial, np.log10(testerror), label='Test Error')
plt.xlabel('Polynomial degree')
plt.ylabel('log10[MSE]')
plt.legend()
plt.show()Degree of polynomial: 1 Mean squared error on training data: 452833.19458364 Mean squared error on test data: 429773.88954087 Degree of polynomial: 2 Mean squared error on training data: 115870.66701669 Mean squared error on test data: 123112.72459873 Degree of polynomial: 3 Mean squared error on training data: 9004.82954042 Mean squared error on test data: 10869.87549153 Degree of polynomial: 4 Mean squared error on training data: 302.39419906 Mean squared error on test data: 427.32079061 Degree of polynomial: 5 Mean squared error on training data: 3.72578939 Mean squared error on test data: 6.84645891 Degree of polynomial: 6 Mean squared error on training data: 3.57820785 Mean squared error on test data: 10.09754281 Degree of polynomial: 7 Mean squared error on training data: 0.47222838 Mean squared error on test data: 1.71423866 Degree of polynomial: 8 Mean squared error on training data: 0.04911195 Mean squared error on test data: 0.13922321 Degree of polynomial: 9 Mean squared error on training data: 0.02536117 Mean squared error on test data: 0.10775110 Degree of polynomial: 10 Mean squared error on training data: 0.02456016 Mean squared error on test data: 0.30553897 Degree of polynomial: 11 Mean squared error on training data: 0.01588176 Mean squared error on test data: 0.34429506 Degree of polynomial: 12 Mean squared error on training data: 0.00813246 Mean squared error on test data: 0.05122248 Degree of polynomial: 13 Mean squared error on training data: 0.00777433 Mean squared error on test data: 0.55694499 Degree of polynomial: 14 Mean squared error on training data: 0.00463992 Mean squared error on test data: 0.41041598 Degree of polynomial: 15 Mean squared error on training data: 0.00412983 Mean squared error on test data: 568.86093965 Degree of polynomial: 16 Mean squared error on training data: 0.00325020 Mean squared error on test data: 40.41455407 Degree of polynomial: 17 Mean squared error on training data: 0.00244533 Mean squared error on test data: 1249.28074263 Degree of polynomial: 18 Mean squared error on training data: 0.00214983 Mean squared error on test data: 205.22625889 Degree of polynomial: 19 Mean squared error on training data: 0.00200171 Mean squared error on test data: 280.68624420 Degree of polynomial: 20 Mean squared error on training data: 0.00155500 Mean squared error on test data: 25.13660834 Degree of polynomial: 21 Mean squared error on training data: 0.00156388 Mean squared error on test data: 77.94529437 Degree of polynomial: 22 Mean squared error on training data: 0.00151469 Mean squared error on test data: 245.67520784 Degree of polynomial: 23 Mean squared error on training data: 0.00130016 Mean squared error on test data: 124.77716463 Degree of polynomial: 24 Mean squared error on training data: 0.00112865 Mean squared error on test data: 1589.08344068 Degree of polynomial: 25 Mean squared error on training data: 0.00101815 Mean squared error on test data: 585.19168405 Degree of polynomial: 26 Mean squared error on training data: 0.00093173 Mean squared error on test data: 97.00573316 Degree of polynomial: 27 Mean squared error on training data: 0.00087876 Mean squared error on test data: 151.60571945 Degree of polynomial: 28 Mean squared error on training data: 0.00092360 Mean squared error on test data: 307.35851187 Degree of polynomial: 29 Mean squared error on training data: 0.00088450 Mean squared error on test data: 577.01491993
/var/folders/td/3yk470mj5p931p9dtkk0y6jw0000gn/T/ipykernel_30869/626635268.py:73: RuntimeWarning: divide by zero encountered in log10 plt.plot(polynomial, np.log10(trainingerror), label='Training Error') /var/folders/td/3yk470mj5p931p9dtkk0y6jw0000gn/T/ipykernel_30869/626635268.py:74: RuntimeWarning: divide by zero encountered in log10 plt.plot(polynomial, np.log10(testerror), label='Test Error')
In [11]:
# Common imports
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
# Where to save the figures and data files
PROJECT_ROOT_DIR = "Results"
FIGURE_ID = "Results/FigureFiles"
DATA_ID = "DataFiles/"
if not os.path.exists(PROJECT_ROOT_DIR):
os.mkdir(PROJECT_ROOT_DIR)
if not os.path.exists(FIGURE_ID):
os.makedirs(FIGURE_ID)
if not os.path.exists(DATA_ID):
os.makedirs(DATA_ID)
def image_path(fig_id):
return os.path.join(FIGURE_ID, fig_id)
def data_path(dat_id):
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
plt.savefig(image_path(fig_id) + ".png", format='png')
infile = open(data_path("EoS.csv"),'r')
# Read the EoS data as csv file and organize the data into two arrays with density and energies
EoS = pd.read_csv(infile, names=('Density', 'Energy'))
EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
EoS = EoS.dropna()
Energies = EoS['Energy']
Density = EoS['Density']
# The design matrix now as function of various polytrops
Maxpolydegree = 30
X = np.zeros((len(Density),Maxpolydegree))
X[:,0] = 1.0
estimated_mse_sklearn = np.zeros(Maxpolydegree)
polynomial = np.zeros(Maxpolydegree)
k =10
kfold = KFold(n_splits = k)
for polydegree in range(1, Maxpolydegree):
polynomial[polydegree] = polydegree
for degree in range(polydegree):
X[:,degree] = Density**(degree/3.0)
OLS = LinearRegression(fit_intercept=False)
# loop over trials in order to estimate the expectation value of the MSE
estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)
#[:, np.newaxis]
estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)
plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')
plt.xlabel('Polynomial degree')
plt.ylabel('log10[MSE]')
plt.legend()
plt.show()/var/folders/td/3yk470mj5p931p9dtkk0y6jw0000gn/T/ipykernel_30869/3127697733.py:63: RuntimeWarning: divide by zero encountered in log10 plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')
In [6]:
# Common imports
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.model_selection import train_test_split
from sklearn.utils import resample
from sklearn.metrics import mean_squared_error
from IPython.display import display
from pylab import plt, mpl
mpl.rcParams['font.family'] = 'serif'
# Where to save the figures and data files
PROJECT_ROOT_DIR = "Results"
FIGURE_ID = "Results/FigureFiles"
DATA_ID = "DataFiles/"
if not os.path.exists(PROJECT_ROOT_DIR):
os.mkdir(PROJECT_ROOT_DIR)
if not os.path.exists(FIGURE_ID):
os.makedirs(FIGURE_ID)
if not os.path.exists(DATA_ID):
os.makedirs(DATA_ID)
def image_path(fig_id):
return os.path.join(FIGURE_ID, fig_id)
def data_path(dat_id):
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
plt.savefig(image_path(fig_id) + ".png", format='png')
infile = open(data_path("chddata.csv"),'r')
# Read the chd data as csv file and organize the data into arrays with age group, age, and chd
chd = pd.read_csv(infile, names=('ID', 'Age', 'Agegroup', 'CHD'))
chd.columns = ['ID', 'Age', 'Agegroup', 'CHD']
output = chd['CHD']
age = chd['Age']
agegroup = chd['Agegroup']
numberID = chd['ID']
display(chd)
plt.scatter(age, output, marker='o')
plt.axis([18,70.0,-0.1, 1.2])
plt.xlabel(r'Age')
plt.ylabel(r'CHD')
plt.title(r'Age distribution and Coronary heart disease')
plt.show()In [7]:
agegroupmean = np.array([0.1, 0.133, 0.250, 0.333, 0.462, 0.625, 0.765, 0.800])
group = np.array([1, 2, 3, 4, 5, 6, 7, 8])
plt.plot(group, agegroupmean, "r-")
plt.axis([0,9,0, 1.0])
plt.xlabel(r'Age group')
plt.ylabel(r'CHD mean values')
plt.title(r'Mean values for each age group')
plt.show()In [8]:
"""The sigmoid function (or the logistic curve) is a
function that takes any real number, z, and outputs a number (0,1).
It is useful in neural networks for assigning weights on a relative scale.
The value z is the weighted sum of parameters involved in the learning algorithm."""
import numpy
import matplotlib.pyplot as plt
import math as mt
z = numpy.arange(-5, 5, .1)
sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z)))
sigma = sigma_fn(z)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(z, sigma)
ax.set_ylim([-0.1, 1.1])
ax.set_xlim([-5,5])
ax.grid(True)
ax.set_xlabel('z')
ax.set_title('sigmoid function')
plt.show()
"""Step Function"""
z = numpy.arange(-5, 5, .02)
step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)
step = step_fn(z)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(z, step)
ax.set_ylim([-0.5, 1.5])
ax.set_xlim([-5,5])
ax.grid(True)
ax.set_xlabel('z')
ax.set_title('step function')
plt.show()
"""tanh Function"""
z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1)
t = numpy.tanh(z)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(z, t)
ax.set_ylim([-1.0, 1.0])
ax.set_xlim([-2*mt.pi,2*mt.pi])
ax.grid(True)
ax.set_xlabel('z')
ax.set_title('tanh function')
plt.show()Warning:
Output truncated. This notebook contains too many cells to display efficiently.
