diff --git a/doc/src/DimRed/DimRed-bs.html b/doc/src/DimRed/DimRed-bs.html deleted file mode 100644 index 701588387..000000000 --- a/doc/src/DimRed/DimRed-bs.html +++ /dev/null @@ -1,249 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Preprocessing and Dimensionality Reduction - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -

 

 

 

- - - - - - -
-

Data Analysis and Machine Learning: Preprocessing and Dimensionality Reduction

- -

- - -

-Morten Hjorth-Jensen [1, 2] -
- -

- - -

[1] Department of Physics, University of Oslo
-
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
-
-

-

Oct 22, 2019

-
-

- - -

Read »

- - -
- -

- -

- - -
- - - - - - - -
- © 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
- - - - - - diff --git a/doc/src/DimRed/DimRed-minted.pdf b/doc/src/DimRed/DimRed-minted.pdf deleted file mode 100644 index 035ad9731..000000000 Binary files a/doc/src/DimRed/DimRed-minted.pdf and /dev/null differ diff --git a/doc/src/DimRed/DimRed-plain-minted.tex b/doc/src/DimRed/DimRed-plain-minted.tex deleted file mode 100644 index a10b4ab77..000000000 --- a/doc/src/DimRed/DimRed-plain-minted.tex +++ /dev/null @@ -1,1042 +0,0 @@ -%% -%% Automatically generated file from DocOnce source -%% (https://github.com/hplgit/doconce/) -%% -%% - - -%-------------------- begin preamble ---------------------- - -\documentclass[% -oneside, % oneside: electronic viewing, twoside: printing -final, % draft: marks overfull hboxes, figures with paths -10pt]{article} - -\listfiles % print all files needed to compile this document - -\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb} -\usepackage[table]{xcolor} -\usepackage{bm,ltablex,microtype} - -\usepackage[pdftex]{graphicx} - -\usepackage{fancyvrb} % packages needed for verbatim environments -\usepackage{minted} -\usemintedstyle{default} - -\usepackage[T1]{fontenc} -%\usepackage[latin1]{inputenc} -\usepackage{ucs} -\usepackage[utf8x]{inputenc} - -\usepackage{lmodern} % Latin Modern fonts derived from Computer Modern - -% Hyperlinks in PDF: -\definecolor{linkcolor}{rgb}{0,0,0.4} -\usepackage{hyperref} -\hypersetup{ - breaklinks=true, - colorlinks=true, - linkcolor=linkcolor, - urlcolor=linkcolor, - citecolor=black, - filecolor=black, - %filecolor=blue, - pdfmenubar=true, - pdftoolbar=true, - bookmarksdepth=3 % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC - } -%\hyperbaseurl{} % hyperlinks are relative to this root - -\setcounter{tocdepth}{2} % levels in table of contents - -% --- fancyhdr package for fancy headers --- -\usepackage{fancyhdr} -\fancyhf{} % sets both header and footer to nothing -\renewcommand{\headrulewidth}{0pt} -\fancyfoot[LE,RO]{\thepage} -% Ensure copyright on titlepage (article style) and chapter pages (book style) -\fancypagestyle{plain}{ - \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} -% \renewcommand{\footrulewidth}{0mm} - \renewcommand{\headrulewidth}{0mm} -} -% Ensure copyright on titlepages with \thispagestyle{empty} -\fancypagestyle{empty}{ - \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} - \renewcommand{\footrulewidth}{0mm} - \renewcommand{\headrulewidth}{0mm} -} - -\pagestyle{fancy} - - -\usepackage[framemethod=TikZ]{mdframed} - -% --- begin definitions of admonition environments --- - -% --- end of definitions of admonition environments --- - -% prevent orhpans and widows -\clubpenalty = 10000 -\widowpenalty = 10000 - -% --- end of standard preamble for documents --- - - -% insert custom LaTeX commands... - -\raggedbottom -\makeindex -\usepackage[totoc]{idxlayout} % for index in the toc -\usepackage[nottoc]{tocbibind} % for references/bibliography in the toc - -%-------------------- end preamble ---------------------- - -\begin{document} - -% matching end for #ifdef PREAMBLE - -\newcommand{\exercisesection}[1]{\subsection*{#1}} - - -% ------------------- main content ---------------------- - - - -% ----------------- title ------------------------- - -\thispagestyle{empty} - -\begin{center} -{\LARGE\bf -\begin{spacing}{1.25} -Data Analysis and Machine Learning: Preprocessing and Dimensionality Reduction -\end{spacing} -} -\end{center} - -% ----------------- author(s) ------------------------- - -\begin{center} -{\bf Morten Hjorth-Jensen${}^{1, 2}$} \\ [0mm] -\end{center} - -\begin{center} -% List of all institutions: -\centerline{{\small ${}^1$Department of Physics, University of Oslo}} -\centerline{{\small ${}^2$Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University}} -\end{center} - -% ----------------- end author(s) ------------------------- - -% --- begin date --- -\begin{center} -Oct 22, 2019 -\end{center} -% --- end date --- - -\vspace{1cm} - - -% !split -\subsection*{Reducing the number of degrees of freedom, overarching view} - -% --- begin paragraph admon --- -\paragraph{} - -Many Machine Learning problems involve thousands or even millions of -features for each training instance. Not only does this make training -extremely slow, it can also make it much harder to find a good -solution, as we will see. This problem is often referred to as the -curse of dimensionality. Fortunately, in real-world problems, it is -often possible to reduce the number of features considerably, turning -an intractable problem into a tractable one. - -Here we will discuss some of the most popular dimensionality reduction -techniques: the principal component analysis PCA, Kernel PCA, and -Locally Linear Embedding (LLE). Furthermore, we will start by looking -at some simple preprocessing of the data which allow us to rescale the -data. -% --- end paragraph admon --- - - - - -% !split -\subsection*{Preprocessing our data} - -% --- begin paragraph admon --- -\paragraph{} - -Before we proceed however, we will discuss how to preprocess our -data. Till now and in connection with our previous examples we have -not met so many cases where we are too sensitive to the scaling of our -data. Normally the data may need a rescaling and/or may be sensitive -to extreme values. Scaling the data renders our inputs much more -suitable for the algorithms we want to employ. - -\textbf{Scikit-Learn} has several functions which allow us to rescale the -data, normally resulting in much better results in terms of various -accuracy scores. The \textbf{StandardScaler} function in \textbf{Scikit-Learn} -ensures that for each feature/predictor we study the mean value is -zero and the variance is one (every column in the design/feature -matrix). This scaling has the drawback that it does not ensure that -we have a particular maximum or minimum in our data set. Another -function included in \textbf{Scikit-Learn} is the \textbf{MinMaxScaler} which -ensures that all features are exactly between $0$ and $1$. The - -% !split -\subsection*{More preprocessing} - - -The \textbf{Normalizer} scales each data -point such that the feature vector has a euclidean length of one. In other words, it -projects a data point on the circle (or sphere in the case of higher dimensions) with a -radius of 1. This means every data point is scaled by a different number (by the -inverse of it’s length). -This normalization is often used when only the direction (or angle) of the data matters, -not the length of the feature vector. - -The \textbf{RobustScaler} works similarly to the StandardScaler in that it -ensures statistical properties for each feature that guarantee that -they are on the same scale. However, the RobustScaler uses the median -and quartiles, instead of mean and variance. This makes the -RobustScaler ignore data points that are very different from the rest -(like measurement errors). These odd data points are also called -outliers, and might often lead to trouble for other scaling -techniques. -% --- end paragraph admon --- - - - -% !split -\subsection*{Simple preprocessing examples, Franke function and regression} - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -# Common imports -import os -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -import sklearn.linear_model as skl -from sklearn.metrics import mean_squared_error -from sklearn.model_selection import train_test_split -from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer -from sklearn.svm import SVR - -# 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') - - -def FrankeFunction(x,y): - term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2)) - term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1)) - term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2)) - term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2) - return term1 + term2 + term3 + term4 - - -def create_X(x, y, n ): - if len(x.shape) > 1: - x = np.ravel(x) - y = np.ravel(y) - - N = len(x) - l = int((n+1)*(n+2)/2) # Number of elements in beta - X = np.ones((N,l)) - - for i in range(1,n+1): - q = int((i)*(i+1)/2) - for k in range(i+1): - X[:,q+k] = (x**(i-k))*(y**k) - - return X - - -# Making meshgrid of datapoints and compute Franke's function -n = 5 -N = 1000 -x = np.sort(np.random.uniform(0, 1, N)) -y = np.sort(np.random.uniform(0, 1, N)) -z = FrankeFunction(x, y) -X = create_X(x, y, n=n) -# split in training and test data -X_train, X_test, y_train, y_test = train_test_split(X,z,test_size=0.2) - - -svm = SVR(gamma='auto',C=10.0) -svm.fit(X_train, y_train) - -# The mean squared error and R2 score -print("MSE before scaling: {:.2f}".format(mean_squared_error(svm.predict(X_test), y_test))) -print("R2 score before scaling {:.2f}".format(svm.score(X_test,y_test))) - -scaler = StandardScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) - -print("Feature min values before scaling:\n {}".format(X_train.min(axis=0))) -print("Feature max values before scaling:\n {}".format(X_train.max(axis=0))) - -print("Feature min values after scaling:\n {}".format(X_train_scaled.min(axis=0))) -print("Feature max values after scaling:\n {}".format(X_train_scaled.max(axis=0))) - -svm = SVR(gamma='auto',C=10.0) -svm.fit(X_train_scaled, y_train) - -print("MSE after scaling: {:.2f}".format(mean_squared_error(svm.predict(X_test_scaled), y_test))) -print("R2 score for scaled data: {:.2f}".format(svm.score(X_test_scaled,y_test))) - -\end{minted} - - - -% !split -\subsection*{Simple preprocessing examples, breast cancer data and classification, Support Vector Machines} - -We show here how we can use a simple regression case on the breast -cancer data using support vector machines (SVM) as algorithm for -classification. - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import matplotlib.pyplot as plt -import numpy as np -from sklearn.model_selection import train_test_split -from sklearn.datasets import load_breast_cancer -from sklearn.svm import SVC -cancer = load_breast_cancer() - -X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0) -print(X_train.shape) -print(X_test.shape) - -svm = SVC(C=100) -svm.fit(X_train, y_train) -print("Test set accuracy: {:.2f}".format(svm.score(X_test,y_test))) - -from sklearn.preprocessing import MinMaxScaler, StandardScaler -scaler = MinMaxScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) - -print("Feature min values before scaling:\n {}".format(X_train.min(axis=0))) -print("Feature max values before scaling:\n {}".format(X_train.max(axis=0))) - -print("Feature min values before scaling:\n {}".format(X_train_scaled.min(axis=0))) -print("Feature max values before scaling:\n {}".format(X_train_scaled.max(axis=0))) - - -svm.fit(X_train_scaled, y_train) -print("Test set accuracy scaled data with Min-Max scaling: {:.2f}".format(svm.score(X_test_scaled,y_test))) - -scaler = StandardScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) - -svm.fit(X_train_scaled, y_train) -print("Test set accuracy scaled data with Standar Scaler: {:.2f}".format(svm.score(X_test_scaled,y_test))) - -\end{minted} - -% !split -\subsection*{More on Cancer Data, now with Logistic Regression} - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import matplotlib.pyplot as plt -import numpy as np -from sklearn.model_selection import train_test_split -from sklearn.datasets import load_breast_cancer -from sklearn.linear_model import LogisticRegression -cancer = load_breast_cancer() - -# Set up training data -X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0) -logreg = LogisticRegression() -logreg.fit(X_train, y_train) -print("Test set accuracy: {:.2f}".format(logreg.score(X_test,y_test))) - -# Scale data -from sklearn.preprocessing import StandardScaler -scaler = StandardScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) -logreg.fit(X_train_scaled, y_train) -print("Test set accuracy scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) - -\end{minted} - - - - -% !split -\subsection*{Why should we think of reducing the dimensionality} - -In addition to the plot of the features, we study now also the covariance (or rather the correlation matrix). -We use also \textbf{Pandas} to compute the correlation matrix. -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import matplotlib.pyplot as plt -import numpy as np -from sklearn.model_selection import train_test_split -from sklearn.datasets import load_breast_cancer -from sklearn.linear_model import LogisticRegression -cancer = load_breast_cancer() -import pandas as pd -# Making a data frame -cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names) - -fig, axes = plt.subplots(15,2,figsize=(10,20)) -malignant = cancer.data[cancer.target == 0] -benign = cancer.data[cancer.target == 1] -ax = axes.ravel() - -for i in range(30): - _, bins = np.histogram(cancer.data[:,i], bins =50) - ax[i].hist(malignant[:,i], bins = bins, alpha = 0.5) - ax[i].hist(benign[:,i], bins = bins, alpha = 0.5) - ax[i].set_title(cancer.feature_names[i]) - ax[i].set_yticks(()) -ax[0].set_xlabel("Feature magnitude") -ax[0].set_ylabel("Frequency") -ax[0].legend(["Malignant", "Benign"], loc ="best") -fig.tight_layout() -plt.show() - -import seaborn as sns -correlation_matrix = cancerpd.corr().round(1) -# use the heatmap function from seaborn to plot the correlation matrix -# annot = True to print the values inside the square -sns.heatmap(data=correlation_matrix, annot=True) -plt.show() - -#print eigvalues of correlation matrix -EigValues, EigVectors = np.linalg.eig(correlation_matrix) -print(EigValues) -\end{minted} - -In the above example we note two things. In the first plot we display -the overlap of benign and malignant tumors as functions of the various -features in the Wisconsing breast cancer data set. We see that for -some of the features we can distinguish clearly the benign and -malignant cases while for other features we cannot. This can point to -us which features may be of greater interest when we wish to classify -a benign or not benign tumour. - -In the second figure we have computed the so-called correlation -matrix, which in our case with thirty features becomes a $30\times 30$ -matrix. - -We constructed this matrix using \textbf{pandas} via the statements -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names) -\end{minted} -and then -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -correlation_matrix = cancerpd.corr().round(1) -\end{minted} - -Diagonalizing this matrix we can in turn say something about which -features are of relevance and which are not. But before we proceed we -need to define covariance and correlation matrices. This leads us to -the classical Principal Component Analysis (PCA) theorem with -applications. - - - -% !split -\subsection*{Basic ideas of the Principal Component Analysis (PCA)} - -We have a data set defined by a design/feature matrix $\bm{X}$ (see below for its definition) -\begin{itemize} -\item Each data point is determined by $p$ extrinsic (measurement) variables - -\item We may want to ask the following question: Are there fewer intrinsic variables (say $d << p$) that still approximately describe the data? - -\item If so, these intrinsic variables may tell us something important and finding these intrinsic variables is what dimension reduction methods do. -\end{itemize} - -\noindent -% !split -\subsection*{Introducing the Covariance and Correlation functions} - -Before we discuss the PCA theorem, we need to remind ourselves about -the definition of the covariance and the correlation function. - -Suppose we have defined two vectors -$\hat{x}$ and $\hat{y}$ with $n$ elements each. The covariance matrix $\bm{C}$ is defined as -\[ -\bm{C}[\bm{x},\bm{y}] = \begin{bmatrix} \mathrm{cov}[\bm{x},\bm{x}] & \mathrm{cov}[\bm{x},\bm{y}] \\ - \mathrm{cov}[\bm{y},\bm{x}] & \mathrm{cov}[\bm{y},\bm{y}] \\ - \end{bmatrix}, -\] -where for example -\[ -\mathrm{cov}[\bm{x},\bm{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). -\] -With this definition and recalling that the variance is defined as -\[ -\mathrm{var}[\bm{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2, -\] -we can rewrite the covariance matrix as -\[ -\bm{C}[\bm{x},\bm{y}] = \begin{bmatrix} \mathrm{var}[\bm{x}] & \mathrm{cov}[\bm{x},\bm{y}] \\ - \mathrm{cov}[\bm{x},\bm{y}] & \mathrm{var}[\bm{y}] \\ - \end{bmatrix}. -\] - -The covariance takes values between zero and infinity and may thus -lead to problems with loss of numerical precision for particularly -large values. It is common to scale the covariance matrix by -introducing instead the correlation matrix defined via the so-called -correlation function - -\[ -\mathrm{corr}[\bm{x},\bm{y}]=\frac{\mathrm{cov}[\bm{x},\bm{y}]}{\sqrt{\mathrm{var}[\bm{x}] \mathrm{var}[\bm{y}]}}. -\] - -The correlation function is then given by values $\mathrm{corr}[\bm{x},\bm{y}] -\in [-1,1]$. This avoids eventual problems with too large values. We -can then define the correlation matrix for the two vectors $\bm{x}$ -and $\bm{y}$ as - -\[ -\bm{K}[\bm{x},\bm{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\bm{x},\bm{y}] \\ - \mathrm{corr}[\bm{y},\bm{x}] & 1 \\ - \end{bmatrix}, -\] - -In the above example this is the function we constructed using \textbf{pandas}. - -% !split -\subsection*{Correlation Function and Design/Feature Matrix} - -In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression we defined the design/feature matrix $\bm{X}$ as -\[ -\bm{X}=\begin{bmatrix} -x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ -x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ -x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ -\dots & \dots & \dots & \dots \dots & \dots \\ -x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ -x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ -\end{bmatrix}, -\] -with $\bm{X}\in {\mathbb{R}}^{n\times p}$, with the predictors/features $p$ refering to the column numbers and the -entries $n$ being the row elements. -We can rewrite the design/feature matrix in terms of its column vectors as -\[ -\bm{X}=\begin{bmatrix} \bm{x}_0 & \bm{x}_0 & \bm{x}_0 & \dots & \dots & \bm{x}_{p-1}\end{bmatrix}, -\] -with a given vector -\[ -\bm{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}. -\] - -With these definitions, we can now rewrite our $2\times 2$ correaltion/covariance matrix in terms of a moe general design/feature matrix $\bm{X}\in {\mathbb{R}}^{n\times p}$. This leads to a $p\times p$ covariance matrix for the vectors $\bm{x}_i$ with $i =0,1,\dots,p-1$ -\[ -\bm{C}[\bm{x}] = \begin{bmatrix} -\mathrm{var}[\bm{x}_0] & \mathrm{cov}[\bm{x}_0,\bm{x}_1] & \mathrm{cov}[\bm{x}_0,\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_0,\bm{x}_{p-1}]\\ -\mathrm{cov}[\bm{x}_1,\bm{x}_0] & \mathrm{var}[\bm{x}_1] & \mathrm{cov}[\bm{x}_1,\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_1,\bm{x}_{p-1}]\\ -\mathrm{cov}[\bm{x}_2,\bm{x}_0] & \mathrm{cov}[\bm{x}_2,\bm{x}_1] & \mathrm{var}[\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_2,\bm{x}_{p-1}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\mathrm{cov}[\bm{x}_{p-1},\bm{x}_0] & \mathrm{cov}[\bm{x}_{p-1},\bm{x}_1] & \mathrm{cov}[\bm{x}_{p-1},\bm{x}_{2}] & \dots & \dots & \mathrm{var}[\bm{x}_{p-1}]\\ -\end{bmatrix}, -\] -and the correlation matrix -\[ -\bm{K}[\bm{x}] = \begin{bmatrix} -1 & \mathrm{corr}[\bm{x}_0,\bm{x}_1] & \mathrm{corr}[\bm{x}_0,\bm{x}_2] & \dots & \dots & \mathrm{corr}[\bm{x}_0,\bm{x}_{p-1}]\\ -\mathrm{corr}[\bm{x}_1,\bm{x}_0] & 1 & \mathrm{corr}[\bm{x}_1,\bm{x}_2] & \dots & \dots & \mathrm{corr}[\bm{x}_1,\bm{x}_{p-1}]\\ -\mathrm{corr}[\bm{x}_2,\bm{x}_0] & \mathrm{corr}[\bm{x}_2,\bm{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\bm{x}_2,\bm{x}_{p-1}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\mathrm{corr}[\bm{x}_{p-1},\bm{x}_0] & \mathrm{corr}[\bm{x}_{p-1},\bm{x}_1] & \mathrm{corr}[\bm{x}_{p-1},\bm{x}_{2}] & \dots & \dots & 1\\ -\end{bmatrix}, -\] - - -% !split -\subsection*{Covariance Matrix Examples} - - -The Numpy function \textbf{np.cov} calculates the covariance elements using -the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have -the exact mean values. The following simple function uses the -\textbf{np.vstack} function which takes each vector of dimension $1\times n$ -and produces a $2\times n$ matrix $\bm{W}$ - - -\[ -\bm{W} = \begin{bmatrix} x_0 & y_0 \\ - x_1 & y_1 \\ - x_2 & y_2\\ - \dots & \dots \\ - x_{n-2} & y_{n-2}\\ - x_{n-1} & y_{n-1} & - \end{bmatrix}, -\] - -which in turn is converted into into the $2\times 2$ covariance matrix -$\bm{C}$ via the Numpy function \textbf{np.cov()}. We note that we can also calculate -the mean value of each set of samples $\bm{x}$ etc using the Numpy -function \textbf{np.mean(x)}. We can also extract the eigenvalues of the -covariance matrix through the \textbf{np.linalg.eig()} function. - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -# Importing various packages -import numpy as np -n = 100 -x = np.random.normal(size=n) -print(np.mean(x)) -y = 4+3*x+np.random.normal(size=n) -print(np.mean(y)) -W = np.vstack((x, y)) -C = np.cov(W) -print(C) -\end{minted} - -% !split -\subsection*{Correlation Matrix} - -The previous example can be converted into the correlation matrix by -simply scaling the matrix elements with the variances. We should also -subtract the mean values for each column. This leads to the following -code which sets up the correlations matrix for the previous example in -a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the $2\times 2$ correlation matrix (since we have only two vectors). - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import numpy as np -n = 100 -# define two vectors -x = np.random.random(size=n) -y = 4+3*x+np.random.normal(size=n) -#scaling the x and y vectors -x = x - np.mean(x) -y = y - np.mean(y) -variance_x = np.sum(x@x)/n -variance_y = np.sum(y@y)/n -print(variance_x) -print(variance_y) -cov_xy = np.sum(x@y)/n -cov_xx = np.sum(x@x)/n -cov_yy = np.sum(y@y)/n -C = np.zeros((2,2)) -C[0,0]= cov_xx/variance_x -C[1,1]= cov_yy/variance_y -C[0,1]= cov_xy/np.sqrt(variance_y*variance_x) -C[1,0]= C[0,1] -print(C) -\end{minted} - -We see that the matrix elements along the diagonal are one as they -should be and that the matrix is symmetric. Furthermore, diagonalizing -this matrix we easily see that it is a positive definite matrix. - -The above procedure with \textbf{numpy} can be made more compact if we use \textbf{pandas}. - -% !split -\subsection*{Correlation Matrix with Pandas} - -We whow here how we can set up the correlation matrix using \textbf{pandas}, as done in this simple code -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import numpy as np -import pandas as pd -n = 10 -x = np.random.normal(size=n) -x = x - np.mean(x) -y = 4+3*x+np.random.normal(size=n) -y = y - np.mean(y) -X = (np.vstack((x, y))).T -print(X) -Xpd = pd.DataFrame(X) -print(Xpd) -correlation_matrix = Xpd.corr() -print(correlation_matrix) -\end{minted} - - -We expand this model to the Franke function discussed above. - -% !split -\subsection*{Correlation Matrix with Pandas and the Franke function} - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -# Common imports -import numpy as np -import pandas as pd - - -def FrankeFunction(x,y): - term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2)) - term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1)) - term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2)) - term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2) - return term1 + term2 + term3 + term4 - - -def create_X(x, y, n ): - if len(x.shape) > 1: - x = np.ravel(x) - y = np.ravel(y) - - N = len(x) - l = int((n+1)*(n+2)/2) # Number of elements in beta - X = np.ones((N,l)) - - for i in range(1,n+1): - q = int((i)*(i+1)/2) - for k in range(i+1): - X[:,q+k] = (x**(i-k))*(y**k) - - return X - - -# Making meshgrid of datapoints and compute Franke's function -n = 4 -N = 100 -x = np.sort(np.random.uniform(0, 1, N)) -y = np.sort(np.random.uniform(0, 1, N)) -z = FrankeFunction(x, y) -X = create_X(x, y, n=n) - -Xpd = pd.DataFrame(X) -# subtract the mean values and set up the covariance matrix -Xpd = Xpd - Xpd.mean() -covariance_matrix = Xpd.cov() -print(covariance_matrix) -\end{minted} - -We note here that the covariance is zero for the first rows and -columns since all matrix elements in the design matrix were set to one -(we are fitting the function in terms of a polynomial of degree $n$). - -This means that the variance for these elements will be zero and will -cause problems when we set up the correlation matrix. We can simply -drop these elements as follows and then construct the correlation -matrix. - - -% !split -\subsection*{Rewriting the Covariance and/or Correlation Matrix} - -We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\bm{X}$ as -\[ -\bm{C}[\bm{x}] = \frac{1}{n}\bm{X}\bm{X}^T= \mathbb{E}[\bm{X}\bm{X}^T]. -\] - -To see this let us simply look at a design matrix $\bm{X}\in {\mathbb{R}}^{2\times 2}$ -\[ -\bm{X}=\begin{bmatrix} -x_{00} & x_{01}\\ -x_{10} & x_{11}\\ -\end{bmatrix}=\begin{bmatrix} -\bm{x}_{0} & \bm{x}_{1}\\ -\end{bmatrix}. -\] - -If we then compute the expectation value -\[ -\mathbb{E}[\bm{X}\bm{X}^T] = \frac{1}{n}\bm{X}\bm{X}^T=\begin{bmatrix} -x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\ -x_{10}x_{00}+x_{01}x_{11} & x_{10}^2+x_{11}^2\\ -\end{bmatrix}, -\] -which is just -\[ -\bm{C}[\bm{x}_0,\bm{x}_1] = \bm{C}[\bm{x}]=\begin{bmatrix} \mathrm{var}[\bm{x}_0] & \mathrm{cov}[\bm{x}_0,\bm{x}_1] \\ - \mathrm{cov}[\bm{x}_1,\bm{x}_0] & \mathrm{var}[\bm{x}_1] \\ - \end{bmatrix}, -\] -where we wrote $$\bm{C}[\bm{x}_0,\bm{x}_1] = \bm{C}[\bm{x}]$$ to indicate that this the covariance of the vectors $\bm{x}$ of the design/feature matrix $\bm{X}$. - -It is easy to generalize this to a matrix $\bm{X}\in {\mathbb{R}}^{n\times p}$. - - -% !split -\subsection*{Towards the PCA theorem} - -We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as -\[ -\bm{C}[\bm{x}] = \frac{1}{n}\bm{X}\bm{X}^T= \mathbb{E}[\bm{X}\bm{X}^T]. -\] -Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices $\bm{S}$. -These matrices are defined as $\bm{S}\in {\mathbb{R}}^{p\times p}$ and obey the orthogonality requirements $\bm{S}\bm{S}^T=\bm{S}^T\bm{S}=\bm{I}$. The matrix can be written out in terms of the column vectors $\bm{s}_i$ as $\bm{S}=[\bm{s}_0,\bm{s}_1,\dots,\bm{s}_{p-1}]$ and $\bm{s}_i \in {\mathbb{R}}^{p}$. - -Assume also that there is a transformation $\bm{S}\bm{C}[\bm{x}]\bm{S}^T=\bm{C}[\bm{y}]$ such that the new matrix $\bm{C}[\bm{y}]$ is diagonal with elements $[\lambda_0,\lambda_1,\lambda_2,\dots,\lambda_{p-1}]$. - -That is we have -\[ -\bm{C}[\bm{y}] = \mathbb{E}[\bm{S}\bm{X}\bm{X}^T\bm{S}^T]=\bm{S}\bm{C}[\bm{x}]\bm{S}^T, -\] -since the matrix $\bm{S}$ is not a data dependent matrix. Multiplying with $\bm{S}^T$ from the left we have -\[ -\bm{S}^T\bm{C}[\bm{y}] = \bm{C}[\bm{x}]\bm{S}^T, -\] -and since $\bm{C}[\bm{y}]$ is diagonal we have for a given eigenvalue $i$ of the covariance matrix that - -\[ -\bm{S}^T_i\lambda_i = \bm{C}[\bm{x}]\bm{S}^T_i. -\] - -In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is -$\lambda_0 > \lambda_1 > \dots > \lambda_{p-1}$. - -% !split -\subsection*{Classical PCA Theorem} - - - -% !split -\subsection*{Prof of the PCA Theorem} - - - - - - -% !split -\subsection*{Getting started with PCA} - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -# Now add PCA -from sklearn.decomposition import PCA -pca = PCA(n_components = 2) -pca.fit(X_train_scaled) - -X_pca = pca.transform(X_train_scaled) -\end{minted} - - - -% !split -\subsection*{Principal Component Analysis} - -% --- begin paragraph admon --- -\paragraph{} -Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm. -First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it. - -The following Python code uses NumPy’s \textbf{svd()} function to obtain all the principal components of the -training set, then extracts the first two principal components -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -X_centered = X - X.mean(axis=0) -U, s, V = np.linalg.svd(X_centered) -c1 = V.T[:, 0] -c2 = V.T[:, 1] -\end{minted} - -PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering -the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t -forget to center the data first. - -Once you have identified all the principal components, you can reduce the dimensionality of the dataset -down to $d$ dimensions by projecting it onto the hyperplane defined by the first $d$ principal components. -Selecting this hyperplane ensures that the projection will preserve as much variance as possible. -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -W2 = V.T[:, :2] -X2D = X_centered.dot(W2) -\end{minted} - -% !split -\subsection*{PCA and scikit-learn} - -Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The -following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note -that it automatically takes care of centering the data): -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -from sklearn.decomposition import PCA -pca = PCA(n_components = 2) -X2D = pca.fit_transform(X) -\end{minted} -After fitting the PCA transformer to the dataset, you can access the principal components using the -components variable (note that it contains the PCs as horizontal vectors, so, for example, the first -principal component is equal to -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -pca.components_.T[:, 0]). -\end{minted} -Another very useful piece of information is the explained variance ratio of each principal component, -available via the $explained\_variance\_ratio$ variable. It indicates the proportion of the dataset’s -variance that lies along the axis of each principal component. -More material to come here. - -% !split -\subsection*{More on the PCA} - -Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to -choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95\%). -Unless, of course, you are reducing dimensionality for data visualization — in that case you will -generally want to reduce the dimensionality down to 2 or 3. -The following code computes PCA without reducing dimensionality, then computes the minimum number -of dimensions required to preserve 95\% of the training set’s variance: -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -pca = PCA() -pca.fit(X) -cumsum = np.cumsum(pca.explained_variance_ratio_) -d = np.argmax(cumsum >= 0.95) + 1 -\end{minted} -You could then set $n\_components=d$ and run PCA again. However, there is a much better option: instead -of specifying the number of principal components you want to preserve, you can set $n\_components$ to be -a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve: -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -pca = PCA(n_components=0.95) -X_reduced = pca.fit_transform(X) -\end{minted} - -% !split -\subsection*{Incremental PCA} - -One problem with the preceding implementation of PCA is that it requires the whole training set to fit in -memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have -been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch -at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new -instances arrive). - -% !split -\subsection*{Randomized PCA} - -Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic -algorithm that quickly finds an approximation of the first d principal components. Its computational -complexity is $O(m \times d^2)+O(d^3)$, instead of $O(m \times n^2) + O(n^3)$, so it is dramatically faster than the -previous algorithms when $d$ is much smaller than $n$. -% --- end paragraph admon --- - - - - -% !split -\subsection*{Kernel PCA} - -% --- begin paragraph admon --- -\paragraph{} - -The kernel trick is a mathematical technique that implicitly maps instances into a -very high-dimensional space (called the feature space), enabling nonlinear classification and regression -with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature -space corresponds to a complex nonlinear decision boundary in the original space. -It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear -projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at -preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a -twisted manifold. -For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -from sklearn.decomposition import KernelPCA -rbf_pca = KernelPCA(n_components = 2, kernel="rbf", gamma=0.04) -X_reduced = rbf_pca.fit_transform(X) -\end{minted} -% --- end paragraph admon --- - - - - -% !split -\subsection*{LLE} - -Locally Linear Embedding (LLE) is another very powerful nonlinear dimensionality reduction -(NLDR) technique. It is a Manifold Learning technique that does not rely on projections like the previous -algorithms. In a nutshell, LLE works by first measuring how each training instance linearly relates to its -closest neighbors (c.n.), and then looking for a low-dimensional representation of the training set where -these local relationships are best preserved (more details shortly). - - - -% !split -\subsection*{Other techniques} - - -There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn. - -Here are some of the most popular: -\begin{itemize} -\item \textbf{Multidimensional Scaling (MDS)} reduces dimensionality while trying to preserve the distances between the instances. - -\item \textbf{Isomap} creates a graph by connecting each instance to its nearest neighbors, then reduces dimensionality while trying to preserve the geodesic distances between the instances. - -\item \textbf{t-Distributed Stochastic Neighbor Embedding} (t-SNE) reduces dimensionality while trying to keep similar instances close and dissimilar instances apart. It is mostly used for visualization, in particular to visualize clusters of instances in high-dimensional space (e.g., to visualize the MNIST images in 2D). - -\item Linear Discriminant Analysis (LDA) is actually a classification algorithm, but during training it learns the most discriminative axes between the classes, and these axes can then be used to define a hyperplane onto which to project the data. The benefit is that the projection will keep classes as far apart as possible, so LDA is a good technique to reduce dimensionality before running another classification algorithm such as a Support Vector Machine (SVM) classifier discussed in the SVM lectures. -\end{itemize} - -\noindent -Here are other examples where we use the \textbf{DataFrame} functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix -of dimensionality $10\times 5$ and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations. -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import numpy as np -import pandas as pd -from IPython.display import display -np.random.seed(100) -# setting up a 10 x 5 matrix -rows = 10 -cols = 5 -a = np.random.randn(rows,cols) -df = pd.DataFrame(a) -display(df) -print(df.mean()) -print(df.std()) -display(df**2) -\end{minted} - -Thereafter we can select specific columns only and plot final results -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth'] -df.index = np.arange(10) - -display(df) -print(df['Second'].mean() ) -print(df.info()) -print(df.describe()) - -from pylab import plt, mpl -plt.style.use('seaborn') -mpl.rcParams['font.family'] = 'serif' - -df.cumsum().plot(lw=2.0, figsize=(10,6)) -plt.show() - - -df.plot.bar(figsize=(10,6), rot=15) -plt.show() -\end{minted} -We can produce a $4\times 4$ matrix -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -b = np.arange(16).reshape((4,4)) -print(b) -df1 = pd.DataFrame(b) -print(df1) -\end{minted} -and many other operations. - - -% ------------------- end of main content --------------- - -\end{document} - diff --git a/doc/src/DimRed/DimRed-reveal.html b/doc/src/DimRed/DimRed-reveal.html deleted file mode 100644 index d17f342fa..000000000 --- a/doc/src/DimRed/DimRed-reveal.html +++ /dev/null @@ -1,1349 +0,0 @@ - - - - - - - -Data Analysis and Machine Learning: Preprocessing and Dimensionality Reduction - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - -
- - - - - - - - - - - - - - -
- - - - -

Data Analysis and Machine Learning: Preprocessing and Dimensionality Reduction

- -

- - -

-Morten Hjorth-Jensen [1, 2] -
- -

 
- - -

[1] Department of Physics, University of Oslo
-
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
-
-

 
-

Oct 22, 2019

-
-

- -

- © 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
-
- - -
-

Reducing the number of degrees of freedom, overarching view

-
- -

-Many Machine Learning problems involve thousands or even millions of -features for each training instance. Not only does this make training -extremely slow, it can also make it much harder to find a good -solution, as we will see. This problem is often referred to as the -curse of dimensionality. Fortunately, in real-world problems, it is -often possible to reduce the number of features considerably, turning -an intractable problem into a tractable one. - -

-Here we will discuss some of the most popular dimensionality reduction -techniques: the principal component analysis PCA, Kernel PCA, and -Locally Linear Embedding (LLE). Furthermore, we will start by looking -at some simple preprocessing of the data which allow us to rescale the -data. - - -

-
- - -
-

Preprocessing our data

-
- -

-Before we proceed however, we will discuss how to preprocess our -data. Till now and in connection with our previous examples we have -not met so many cases where we are too sensitive to the scaling of our -data. Normally the data may need a rescaling and/or may be sensitive -to extreme values. Scaling the data renders our inputs much more -suitable for the algorithms we want to employ. - -

-Scikit-Learn has several functions which allow us to rescale the -data, normally resulting in much better results in terms of various -accuracy scores. The StandardScaler function in Scikit-Learn -ensures that for each feature/predictor we study the mean value is -zero and the variance is one (every column in the design/feature -matrix). This scaling has the drawback that it does not ensure that -we have a particular maximum or minimum in our data set. Another -function included in Scikit-Learn is the MinMaxScaler which -ensures that all features are exactly between \( 0 \) and \( 1 \). The -

- - -
-

More preprocessing

- -

-The Normalizer scales each data -point such that the feature vector has a euclidean length of one. In other words, it -projects a data point on the circle (or sphere in the case of higher dimensions) with a -radius of 1. This means every data point is scaled by a different number (by the -inverse of it’s length). -This normalization is often used when only the direction (or angle) of the data matters, -not the length of the feature vector. - -

-The RobustScaler works similarly to the StandardScaler in that it -ensures statistical properties for each feature that guarantee that -they are on the same scale. However, the RobustScaler uses the median -and quartiles, instead of mean and variance. This makes the -RobustScaler ignore data points that are very different from the rest -(like measurement errors). These odd data points are also called -outliers, and might often lead to trouble for other scaling -techniques. - - -

- - - -
-

Simple preprocessing examples, Franke function and regression

- -

- - -

# Common imports
-import os
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-import sklearn.linear_model as skl
-from sklearn.metrics import mean_squared_error
-from sklearn.model_selection import  train_test_split
-from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer
-from sklearn.svm import SVR
-
-# 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')
-
-
-def FrankeFunction(x,y):
-	term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
-	term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
-	term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
-	term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
-	return term1 + term2 + term3 + term4
-
-
-def create_X(x, y, n ):
-	if len(x.shape) > 1:
-		x = np.ravel(x)
-		y = np.ravel(y)
-
-	N = len(x)
-	l = int((n+1)*(n+2)/2)		# Number of elements in beta
-	X = np.ones((N,l))
-
-	for i in range(1,n+1):
-		q = int((i)*(i+1)/2)
-		for k in range(i+1):
-			X[:,q+k] = (x**(i-k))*(y**k)
-
-	return X
-
-
-# Making meshgrid of datapoints and compute Franke's function
-n = 5
-N = 1000
-x = np.sort(np.random.uniform(0, 1, N))
-y = np.sort(np.random.uniform(0, 1, N))
-z = FrankeFunction(x, y)
-X = create_X(x, y, n=n)    
-# split in training and test data
-X_train, X_test, y_train, y_test = train_test_split(X,z,test_size=0.2)
-
-
-svm = SVR(gamma='auto',C=10.0)
-svm.fit(X_train, y_train)
-
-# The mean squared error and R2 score
-print("MSE before scaling: {:.2f}".format(mean_squared_error(svm.predict(X_test), y_test)))
-print("R2 score before scaling {:.2f}".format(svm.score(X_test,y_test)))
-
-scaler = StandardScaler()
-scaler.fit(X_train)
-X_train_scaled = scaler.transform(X_train)
-X_test_scaled = scaler.transform(X_test)
-
-print("Feature min values before scaling:\n {}".format(X_train.min(axis=0)))
-print("Feature max values before scaling:\n {}".format(X_train.max(axis=0)))
-
-print("Feature min values after scaling:\n {}".format(X_train_scaled.min(axis=0)))
-print("Feature max values after scaling:\n {}".format(X_train_scaled.max(axis=0)))
-
-svm = SVR(gamma='auto',C=10.0)
-svm.fit(X_train_scaled, y_train)
-
-print("MSE after  scaling: {:.2f}".format(mean_squared_error(svm.predict(X_test_scaled), y_test)))
-print("R2 score for  scaled data: {:.2f}".format(svm.score(X_test_scaled,y_test)))
-
-
- - -
-

Simple preprocessing examples, breast cancer data and classification, Support Vector Machines

- -

-We show here how we can use a simple regression case on the breast -cancer data using support vector machines (SVM) as algorithm for -classification. - -

- - -

import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.model_selection import  train_test_split 
-from sklearn.datasets import load_breast_cancer
-from sklearn.svm import SVC
-cancer = load_breast_cancer()
-
-X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
-print(X_train.shape)
-print(X_test.shape)
-
-svm = SVC(C=100)
-svm.fit(X_train, y_train)
-print("Test set accuracy: {:.2f}".format(svm.score(X_test,y_test)))
-
-from sklearn.preprocessing import MinMaxScaler, StandardScaler
-scaler = MinMaxScaler()
-scaler.fit(X_train)
-X_train_scaled = scaler.transform(X_train)
-X_test_scaled = scaler.transform(X_test)
-
-print("Feature min values before scaling:\n {}".format(X_train.min(axis=0)))
-print("Feature max values before scaling:\n {}".format(X_train.max(axis=0)))
-
-print("Feature min values before scaling:\n {}".format(X_train_scaled.min(axis=0)))
-print("Feature max values before scaling:\n {}".format(X_train_scaled.max(axis=0)))
-
-
-svm.fit(X_train_scaled, y_train)
-print("Test set accuracy scaled data with Min-Max scaling: {:.2f}".format(svm.score(X_test_scaled,y_test)))
-
-scaler = StandardScaler()
-scaler.fit(X_train)
-X_train_scaled = scaler.transform(X_train)
-X_test_scaled = scaler.transform(X_test)
-
-svm.fit(X_train_scaled, y_train)
-print("Test set accuracy scaled data with Standar Scaler: {:.2f}".format(svm.score(X_test_scaled,y_test)))
-
-
- - -
-

More on Cancer Data, now with Logistic Regression

- -

- - -

import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.model_selection import  train_test_split 
-from sklearn.datasets import load_breast_cancer
-from sklearn.linear_model import LogisticRegression
-cancer = load_breast_cancer()
-
-# Set up training data
-X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
-logreg = LogisticRegression()
-logreg.fit(X_train, y_train)
-print("Test set accuracy: {:.2f}".format(logreg.score(X_test,y_test)))
-
-# Scale data
-from sklearn.preprocessing import StandardScaler
-scaler = StandardScaler()
-scaler.fit(X_train)
-X_train_scaled = scaler.transform(X_train)
-X_test_scaled = scaler.transform(X_test)
-logreg.fit(X_train_scaled, y_train)
-print("Test set accuracy scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
-
-
- - -
-

Why should we think of reducing the dimensionality

- -

-In addition to the plot of the features, we study now also the covariance (or rather the correlation matrix). -We use also Pandas to compute the correlation matrix. -

- - -

import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.model_selection import  train_test_split 
-from sklearn.datasets import load_breast_cancer
-from sklearn.linear_model import LogisticRegression
-cancer = load_breast_cancer()
-import pandas as pd
-# Making a data frame
-cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)
-
-fig, axes = plt.subplots(15,2,figsize=(10,20))
-malignant = cancer.data[cancer.target == 0]
-benign = cancer.data[cancer.target == 1]
-ax = axes.ravel()
-
-for i in range(30):
-    _, bins = np.histogram(cancer.data[:,i], bins =50)
-    ax[i].hist(malignant[:,i], bins = bins, alpha = 0.5)
-    ax[i].hist(benign[:,i], bins = bins, alpha = 0.5)
-    ax[i].set_title(cancer.feature_names[i])
-    ax[i].set_yticks(())
-ax[0].set_xlabel("Feature magnitude")
-ax[0].set_ylabel("Frequency")
-ax[0].legend(["Malignant", "Benign"], loc ="best")
-fig.tight_layout()
-plt.show()
-
-import seaborn as sns
-correlation_matrix = cancerpd.corr().round(1)
-# use the heatmap function from seaborn to plot the correlation matrix
-# annot = True to print the values inside the square
-sns.heatmap(data=correlation_matrix, annot=True)
-plt.show()
-
-#print eigvalues of correlation matrix
-EigValues, EigVectors = np.linalg.eig(correlation_matrix)
-print(EigValues)
-
-

-In the above example we note two things. In the first plot we display -the overlap of benign and malignant tumors as functions of the various -features in the Wisconsing breast cancer data set. We see that for -some of the features we can distinguish clearly the benign and -malignant cases while for other features we cannot. This can point to -us which features may be of greater interest when we wish to classify -a benign or not benign tumour. - -

-In the second figure we have computed the so-called correlation -matrix, which in our case with thirty features becomes a \( 30\times 30 \) -matrix. - -

-We constructed this matrix using pandas via the statements -

- - -

cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)
-
-

-and then -

- - -

correlation_matrix = cancerpd.corr().round(1)
-
-

-Diagonalizing this matrix we can in turn say something about which -features are of relevance and which are not. But before we proceed we -need to define covariance and correlation matrices. This leads us to -the classical Principal Component Analysis (PCA) theorem with -applications. -

- - -
-

Basic ideas of the Principal Component Analysis (PCA)

- -

-We have a data set defined by a design/feature matrix \( \boldsymbol{X} \) (see below for its definition) - -

-
- - -
-

Introducing the Covariance and Correlation functions

- -

-Before we discuss the PCA theorem, we need to remind ourselves about -the definition of the covariance and the correlation function. - -

-Suppose we have defined two vectors -\( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as -

 
-$$ -\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{cov}[\boldsymbol{x},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{cov}[\boldsymbol{y},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{y},\boldsymbol{y}] \\ - \end{bmatrix}, -$$ -

 
- -where for example -

 
-$$ -\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). -$$ -

 
- -With this definition and recalling that the variance is defined as -

 
-$$ -\mathrm{var}[\boldsymbol{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2, -$$ -

 
- -we can rewrite the covariance matrix as -

 
-$$ -\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{var}[\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] & \mathrm{var}[\boldsymbol{y}] \\ - \end{bmatrix}. -$$ -

 
- -

-The covariance takes values between zero and infinity and may thus -lead to problems with loss of numerical precision for particularly -large values. It is common to scale the covariance matrix by -introducing instead the correlation matrix defined via the so-called -correlation function - -

 
-$$ -\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}. -$$ -

 
- -

-The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] -\in [-1,1] \). This avoids eventual problems with too large values. We -can then define the correlation matrix for the two vectors \( \boldsymbol{x} \) -and \( \boldsymbol{y} \) as - -

 
-$$ -\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\ - \end{bmatrix}, -$$ -

 
- -

-In the above example this is the function we constructed using pandas. -

- - -
-

Correlation Function and Design/Feature Matrix

- -

-In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression we defined the design/feature matrix \( \boldsymbol{X} \) as -

 
-$$ -\boldsymbol{X}=\begin{bmatrix} -x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ -x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ -x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ -\dots & \dots & \dots & \dots \dots & \dots \\ -x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ -x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ -\end{bmatrix}, -$$ -

 
- -with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the -entries \( n \) being the row elements. -We can rewrite the design/feature matrix in terms of its column vectors as -

 
-$$ -\boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_0 & \boldsymbol{x}_0 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix}, -$$ -

 
- -with a given vector -

 
-$$ -\boldsymbol{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}. -$$ -

 
- -

-With these definitions, we can now rewrite our \( 2\times 2 \) correaltion/covariance matrix in terms of a moe general design/feature matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \) covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i =0,1,\dots,p-1 \) -

 
-$$ -\boldsymbol{C}[\boldsymbol{x}] = \begin{bmatrix} -\mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\ -\mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\ -\mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_1] & \mathrm{var}[\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & \mathrm{var}[\boldsymbol{x}_{p-1}]\\ -\end{bmatrix}, -$$ -

 
- -and the correlation matrix -

 
-$$ -\boldsymbol{K}[\boldsymbol{x}] = \begin{bmatrix} -1 & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\ -\mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_0] & 1 & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\ -\mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & 1\\ -\end{bmatrix}, -$$ -

 
-

- - -
-

Covariance Matrix Examples

- -

-The Numpy function np.cov calculates the covariance elements using -the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have -the exact mean values. The following simple function uses the -np.vstack function which takes each vector of dimension \( 1\times n \) -and produces a \( 2\times n \) matrix \( \boldsymbol{W} \) - -

 
-$$ -\boldsymbol{W} = \begin{bmatrix} x_0 & y_0 \\ - x_1 & y_1 \\ - x_2 & y_2\\ - \dots & \dots \\ - x_{n-2} & y_{n-2}\\ - x_{n-1} & y_{n-1} & - \end{bmatrix}, -$$ -

 
- -

-which in turn is converted into into the \( 2\times 2 \) covariance matrix -\( \boldsymbol{C} \) via the Numpy function np.cov(). We note that we can also calculate -the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy -function np.mean(x). We can also extract the eigenvalues of the -covariance matrix through the np.linalg.eig() function. - -

- - -

# Importing various packages
-import numpy as np
-n = 100
-x = np.random.normal(size=n)
-print(np.mean(x))
-y = 4+3*x+np.random.normal(size=n)
-print(np.mean(y))
-W = np.vstack((x, y))
-C = np.cov(W)
-print(C)
-
-
- - -
-

Correlation Matrix

- -

-The previous example can be converted into the correlation matrix by -simply scaling the matrix elements with the variances. We should also -subtract the mean values for each column. This leads to the following -code which sets up the correlations matrix for the previous example in -a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the \( 2\times 2 \) correlation matrix (since we have only two vectors). - -

- - -

import numpy as np
-n = 100
-# define two vectors                                                                                           
-x = np.random.random(size=n)
-y = 4+3*x+np.random.normal(size=n)
-#scaling the x and y vectors                                                                                   
-x = x - np.mean(x)
-y = y - np.mean(y)
-variance_x = np.sum(x@x)/n
-variance_y = np.sum(y@y)/n
-print(variance_x)
-print(variance_y)
-cov_xy = np.sum(x@y)/n
-cov_xx = np.sum(x@x)/n
-cov_yy = np.sum(y@y)/n
-C = np.zeros((2,2))
-C[0,0]= cov_xx/variance_x
-C[1,1]= cov_yy/variance_y
-C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
-C[1,0]= C[0,1]
-print(C)
-
-

-We see that the matrix elements along the diagonal are one as they -should be and that the matrix is symmetric. Furthermore, diagonalizing -this matrix we easily see that it is a positive definite matrix. - -

-The above procedure with numpy can be made more compact if we use pandas. -

- - -
-

Correlation Matrix with Pandas

- -

-We whow here how we can set up the correlation matrix using pandas, as done in this simple code -

- - -

import numpy as np
-import pandas as pd
-n = 10
-x = np.random.normal(size=n)
-x = x - np.mean(x)
-y = 4+3*x+np.random.normal(size=n)
-y = y - np.mean(y)
-X = (np.vstack((x, y))).T
-print(X)
-Xpd = pd.DataFrame(X)
-print(Xpd)
-correlation_matrix = Xpd.corr()
-print(correlation_matrix)
-
-

-We expand this model to the Franke function discussed above. -

- - -
-

Correlation Matrix with Pandas and the Franke function

- -

- - -

# Common imports
-import numpy as np
-import pandas as pd
-
-
-def FrankeFunction(x,y):
-	term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
-	term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
-	term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
-	term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
-	return term1 + term2 + term3 + term4
-
-
-def create_X(x, y, n ):
-	if len(x.shape) > 1:
-		x = np.ravel(x)
-		y = np.ravel(y)
-
-	N = len(x)
-	l = int((n+1)*(n+2)/2)		# Number of elements in beta
-	X = np.ones((N,l))
-
-	for i in range(1,n+1):
-		q = int((i)*(i+1)/2)
-		for k in range(i+1):
-			X[:,q+k] = (x**(i-k))*(y**k)
-
-	return X
-
-
-# Making meshgrid of datapoints and compute Franke's function
-n = 4
-N = 100
-x = np.sort(np.random.uniform(0, 1, N))
-y = np.sort(np.random.uniform(0, 1, N))
-z = FrankeFunction(x, y)
-X = create_X(x, y, n=n)    
-
-Xpd = pd.DataFrame(X)
-# subtract the mean values and set up the covariance matrix
-Xpd = Xpd - Xpd.mean()
-covariance_matrix = Xpd.cov()
-print(covariance_matrix)
-
-

-We note here that the covariance is zero for the first rows and -columns since all matrix elements in the design matrix were set to one -(we are fitting the function in terms of a polynomial of degree \( n \)). - -

-This means that the variance for these elements will be zero and will -cause problems when we set up the correlation matrix. We can simply -drop these elements as follows and then construct the correlation -matrix. -

- - -
-

Rewriting the Covariance and/or Correlation Matrix

- -

-We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as -

 
-$$ -\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T= \mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T]. -$$ -

 
- -

-To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \) -

 
-$$ -\boldsymbol{X}=\begin{bmatrix} -x_{00} & x_{01}\\ -x_{10} & x_{11}\\ -\end{bmatrix}=\begin{bmatrix} -\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\ -\end{bmatrix}. -$$ -

 
- -

-If we then compute the expectation value -

 
-$$ -\mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T=\begin{bmatrix} -x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\ -x_{10}x_{00}+x_{01}x_{11} & x_{10}^2+x_{11}^2\\ -\end{bmatrix}, -$$ -

 
- -which is just -

 
-$$ -\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]=\begin{bmatrix} \mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] \\ - \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] \\ - \end{bmatrix}, -$$ -

 
- -where we wrote

 
-$$\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]$$ -

 
to indicate that this the covariance of the vectors \( \boldsymbol{x} \) of the design/feature matrix \( \boldsymbol{X} \). - -

-It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). -

- - -
-

Towards the PCA theorem

- -

-We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as -

 
-$$ -\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T= \mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T]. -$$ -

 
- -Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices \( \boldsymbol{S} \). -These matrices are defined as \( \boldsymbol{S}\in {\mathbb{R}}^{p\times p} \) and obey the orthogonality requirements \( \boldsymbol{S}\boldsymbol{S}^T=\boldsymbol{S}^T\boldsymbol{S}=\boldsymbol{I} \). The matrix can be written out in terms of the column vectors \( \boldsymbol{s}_i \) as \( \boldsymbol{S}=[\boldsymbol{s}_0,\boldsymbol{s}_1,\dots,\boldsymbol{s}_{p-1}] \) and \( \boldsymbol{s}_i \in {\mathbb{R}}^{p} \). - -

-Assume also that there is a transformation \( \boldsymbol{S}\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T=\boldsymbol{C}[\boldsymbol{y}] \) such that the new matrix \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal with elements \( [\lambda_0,\lambda_1,\lambda_2,\dots,\lambda_{p-1}] \). - -

-That is we have -

 
-$$ -\boldsymbol{C}[\boldsymbol{y}] = \mathbb{E}[\boldsymbol{S}\boldsymbol{X}\boldsymbol{X}^T\boldsymbol{S}^T]=\boldsymbol{S}\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T, -$$ -

 
- -since the matrix \( \boldsymbol{S} \) is not a data dependent matrix. Multiplying with \( \boldsymbol{S}^T \) from the left we have -

 
-$$ -\boldsymbol{S}^T\boldsymbol{C}[\boldsymbol{y}] = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T, -$$ -

 
- -and since \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal we have for a given eigenvalue \( i \) of the covariance matrix that - -

 
-$$ -\boldsymbol{S}^T_i\lambda_i = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T_i. -$$ -

 
- -

-In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is -\( \lambda_0 > \lambda_1 > \dots > \lambda_{p-1} \). -

- - -
-

Classical PCA Theorem

-
- - -
-

Prof of the PCA Theorem

-
- - -
-

Getting started with PCA

- -

- - -

# Now add PCA
-from sklearn.decomposition import PCA
-pca = PCA(n_components = 2)
-pca.fit(X_train_scaled)
-
-X_pca = pca.transform(X_train_scaled)
-
-
- - -
-

Principal Component Analysis

-
- -

-Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm. -First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it. - -

-The following Python code uses NumPy’s svd() function to obtain all the principal components of the -training set, then extracts the first two principal components -

- - -

X_centered = X - X.mean(axis=0)
-U, s, V = np.linalg.svd(X_centered)
-c1 = V.T[:, 0]
-c2 = V.T[:, 1]
-
-

-PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering -the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t -forget to center the data first. - -

-Once you have identified all the principal components, you can reduce the dimensionality of the dataset -down to \( d \) dimensions by projecting it onto the hyperplane defined by the first \( d \) principal components. -Selecting this hyperplane ensures that the projection will preserve as much variance as possible. -

- - -

W2 = V.T[:, :2]
-X2D = X_centered.dot(W2)
-
-
- - -
-

PCA and scikit-learn

- -

-Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The -following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note -that it automatically takes care of centering the data): -

- - -

from sklearn.decomposition import PCA
-pca = PCA(n_components = 2)
-X2D = pca.fit_transform(X)
-
-

-After fitting the PCA transformer to the dataset, you can access the principal components using the -components variable (note that it contains the PCs as horizontal vectors, so, for example, the first -principal component is equal to -

- - -

pca.components_.T[:, 0]).
-
-

-Another very useful piece of information is the explained variance ratio of each principal component, -available via the \( explained\_variance\_ratio \) variable. It indicates the proportion of the dataset’s -variance that lies along the axis of each principal component. -More material to come here. -

- - -
-

More on the PCA

- -

-Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to -choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%). -Unless, of course, you are reducing dimensionality for data visualization — in that case you will -generally want to reduce the dimensionality down to 2 or 3. -The following code computes PCA without reducing dimensionality, then computes the minimum number -of dimensions required to preserve 95% of the training set’s variance: -

- - -

pca = PCA()
-pca.fit(X)
-cumsum = np.cumsum(pca.explained_variance_ratio_)
-d = np.argmax(cumsum >= 0.95) + 1
-
-

-You could then set \( n\_components=d \) and run PCA again. However, there is a much better option: instead -of specifying the number of principal components you want to preserve, you can set \( n\_components \) to be -a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve: -

- - -

pca = PCA(n_components=0.95)
-X_reduced = pca.fit_transform(X)
-
-
- - -
-

Incremental PCA

- -

-One problem with the preceding implementation of PCA is that it requires the whole training set to fit in -memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have -been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch -at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new -instances arrive). -

- - -
-

Randomized PCA

- -

-Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic -algorithm that quickly finds an approximation of the first d principal components. Its computational -complexity is \( O(m \times d^2)+O(d^3) \), instead of \( O(m \times n^2) + O(n^3) \), so it is dramatically faster than the -previous algorithms when \( d \) is much smaller than \( n \). - - -

- - - -
-

Kernel PCA

-
- -

-The kernel trick is a mathematical technique that implicitly maps instances into a -very high-dimensional space (called the feature space), enabling nonlinear classification and regression -with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature -space corresponds to a complex nonlinear decision boundary in the original space. -It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear -projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at -preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a -twisted manifold. -For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an -

- - -

from sklearn.decomposition import KernelPCA
-rbf_pca = KernelPCA(n_components = 2, kernel="rbf", gamma=0.04)
-X_reduced = rbf_pca.fit_transform(X)
-
- -
-
- - -
-

LLE

- -

-Locally Linear Embedding (LLE) is another very powerful nonlinear dimensionality reduction -(NLDR) technique. It is a Manifold Learning technique that does not rely on projections like the previous -algorithms. In a nutshell, LLE works by first measuring how each training instance linearly relates to its -closest neighbors (c.n.), and then looking for a low-dimensional representation of the training set where -these local relationships are best preserved (more details shortly). -

- - -
-

Other techniques

- -

-There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn. - -

-Here are some of the most popular: - -

-

- -Here are other examples where we use the DataFrame functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix -of dimensionality \( 10\times 5 \) and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations. -

- - -

import numpy as np
-import pandas as pd
-from IPython.display import display
-np.random.seed(100)
-# setting up a 10 x 5 matrix
-rows = 10
-cols = 5
-a = np.random.randn(rows,cols)
-df = pd.DataFrame(a)
-display(df)
-print(df.mean())
-print(df.std())
-display(df**2)
-
-

-Thereafter we can select specific columns only and plot final results -

- - -

df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']
-df.index = np.arange(10)
-
-display(df)
-print(df['Second'].mean() )
-print(df.info())
-print(df.describe())
-
-from pylab import plt, mpl
-plt.style.use('seaborn')
-mpl.rcParams['font.family'] = 'serif'
-
-df.cumsum().plot(lw=2.0, figsize=(10,6))
-plt.show()
-
-
-df.plot.bar(figsize=(10,6), rot=15)
-plt.show()
-
-

-We can produce a \( 4\times 4 \) matrix -

- - -

b = np.arange(16).reshape((4,4))
-print(b)
-df1 = pd.DataFrame(b)
-print(df1)
-
-

-and many other operations. -

- - - - - - - - - - - - - - - - - diff --git a/doc/src/DimRed/DimRed-solarized.html b/doc/src/DimRed/DimRed-solarized.html deleted file mode 100644 index 959e73c3b..000000000 --- a/doc/src/DimRed/DimRed-solarized.html +++ /dev/null @@ -1,1180 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Preprocessing and Dimensionality Reduction - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Data Analysis and Machine Learning: Preprocessing and Dimensionality Reduction

- -

- - -

-Morten Hjorth-Jensen [1, 2] -
- -

- - -

[1] Department of Physics, University of Oslo
-
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
-
-

-

Oct 22, 2019

-
-

-









- -

Reducing the number of degrees of freedom, overarching view

-
- -

- -

-Many Machine Learning problems involve thousands or even millions of -features for each training instance. Not only does this make training -extremely slow, it can also make it much harder to find a good -solution, as we will see. This problem is often referred to as the -curse of dimensionality. Fortunately, in real-world problems, it is -often possible to reduce the number of features considerably, turning -an intractable problem into a tractable one. - -

-Here we will discuss some of the most popular dimensionality reduction -techniques: the principal component analysis PCA, Kernel PCA, and -Locally Linear Embedding (LLE). Furthermore, we will start by looking -at some simple preprocessing of the data which allow us to rescale the -data. - - -

- - -

-









- -

Preprocessing our data

-
- -

- -

-Before we proceed however, we will discuss how to preprocess our -data. Till now and in connection with our previous examples we have -not met so many cases where we are too sensitive to the scaling of our -data. Normally the data may need a rescaling and/or may be sensitive -to extreme values. Scaling the data renders our inputs much more -suitable for the algorithms we want to employ. - -

-Scikit-Learn has several functions which allow us to rescale the -data, normally resulting in much better results in terms of various -accuracy scores. The StandardScaler function in Scikit-Learn -ensures that for each feature/predictor we study the mean value is -zero and the variance is one (every column in the design/feature -matrix). This scaling has the drawback that it does not ensure that -we have a particular maximum or minimum in our data set. Another -function included in Scikit-Learn is the MinMaxScaler which -ensures that all features are exactly between \( 0 \) and \( 1 \). The - -

-









- -

More preprocessing

- -

-The Normalizer scales each data -point such that the feature vector has a euclidean length of one. In other words, it -projects a data point on the circle (or sphere in the case of higher dimensions) with a -radius of 1. This means every data point is scaled by a different number (by the -inverse of it’s length). -This normalization is often used when only the direction (or angle) of the data matters, -not the length of the feature vector. - -

-The RobustScaler works similarly to the StandardScaler in that it -ensures statistical properties for each feature that guarantee that -they are on the same scale. However, the RobustScaler uses the median -and quartiles, instead of mean and variance. This makes the -RobustScaler ignore data points that are very different from the rest -(like measurement errors). These odd data points are also called -outliers, and might often lead to trouble for other scaling -techniques. - - -

- - -

-









- -

Simple preprocessing examples, Franke function and regression

- -

- - -

# Common imports
-import os
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-import sklearn.linear_model as skl
-from sklearn.metrics import mean_squared_error
-from sklearn.model_selection import  train_test_split
-from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer
-from sklearn.svm import SVR
-
-# 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')
-
-
-def FrankeFunction(x,y):
-	term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
-	term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
-	term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
-	term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
-	return term1 + term2 + term3 + term4
-
-
-def create_X(x, y, n ):
-	if len(x.shape) > 1:
-		x = np.ravel(x)
-		y = np.ravel(y)
-
-	N = len(x)
-	l = int((n+1)*(n+2)/2)		# Number of elements in beta
-	X = np.ones((N,l))
-
-	for i in range(1,n+1):
-		q = int((i)*(i+1)/2)
-		for k in range(i+1):
-			X[:,q+k] = (x**(i-k))*(y**k)
-
-	return X
-
-
-# Making meshgrid of datapoints and compute Franke's function
-n = 5
-N = 1000
-x = np.sort(np.random.uniform(0, 1, N))
-y = np.sort(np.random.uniform(0, 1, N))
-z = FrankeFunction(x, y)
-X = create_X(x, y, n=n)    
-# split in training and test data
-X_train, X_test, y_train, y_test = train_test_split(X,z,test_size=0.2)
-
-
-svm = SVR(gamma='auto',C=10.0)
-svm.fit(X_train, y_train)
-
-# The mean squared error and R2 score
-print("MSE before scaling: {:.2f}".format(mean_squared_error(svm.predict(X_test), y_test)))
-print("R2 score before scaling {:.2f}".format(svm.score(X_test,y_test)))
-
-scaler = StandardScaler()
-scaler.fit(X_train)
-X_train_scaled = scaler.transform(X_train)
-X_test_scaled = scaler.transform(X_test)
-
-print("Feature min values before scaling:\n {}".format(X_train.min(axis=0)))
-print("Feature max values before scaling:\n {}".format(X_train.max(axis=0)))
-
-print("Feature min values after scaling:\n {}".format(X_train_scaled.min(axis=0)))
-print("Feature max values after scaling:\n {}".format(X_train_scaled.max(axis=0)))
-
-svm = SVR(gamma='auto',C=10.0)
-svm.fit(X_train_scaled, y_train)
-
-print("MSE after  scaling: {:.2f}".format(mean_squared_error(svm.predict(X_test_scaled), y_test)))
-print("R2 score for  scaled data: {:.2f}".format(svm.score(X_test_scaled,y_test)))
-
-

-









- -

Simple preprocessing examples, breast cancer data and classification, Support Vector Machines

- -

-We show here how we can use a simple regression case on the breast -cancer data using support vector machines (SVM) as algorithm for -classification. - -

- - -

import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.model_selection import  train_test_split 
-from sklearn.datasets import load_breast_cancer
-from sklearn.svm import SVC
-cancer = load_breast_cancer()
-
-X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
-print(X_train.shape)
-print(X_test.shape)
-
-svm = SVC(C=100)
-svm.fit(X_train, y_train)
-print("Test set accuracy: {:.2f}".format(svm.score(X_test,y_test)))
-
-from sklearn.preprocessing import MinMaxScaler, StandardScaler
-scaler = MinMaxScaler()
-scaler.fit(X_train)
-X_train_scaled = scaler.transform(X_train)
-X_test_scaled = scaler.transform(X_test)
-
-print("Feature min values before scaling:\n {}".format(X_train.min(axis=0)))
-print("Feature max values before scaling:\n {}".format(X_train.max(axis=0)))
-
-print("Feature min values before scaling:\n {}".format(X_train_scaled.min(axis=0)))
-print("Feature max values before scaling:\n {}".format(X_train_scaled.max(axis=0)))
-
-
-svm.fit(X_train_scaled, y_train)
-print("Test set accuracy scaled data with Min-Max scaling: {:.2f}".format(svm.score(X_test_scaled,y_test)))
-
-scaler = StandardScaler()
-scaler.fit(X_train)
-X_train_scaled = scaler.transform(X_train)
-X_test_scaled = scaler.transform(X_test)
-
-svm.fit(X_train_scaled, y_train)
-print("Test set accuracy scaled data with Standar Scaler: {:.2f}".format(svm.score(X_test_scaled,y_test)))
-
-

-









- -

More on Cancer Data, now with Logistic Regression

- -

- - -

import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.model_selection import  train_test_split 
-from sklearn.datasets import load_breast_cancer
-from sklearn.linear_model import LogisticRegression
-cancer = load_breast_cancer()
-
-# Set up training data
-X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
-logreg = LogisticRegression()
-logreg.fit(X_train, y_train)
-print("Test set accuracy: {:.2f}".format(logreg.score(X_test,y_test)))
-
-# Scale data
-from sklearn.preprocessing import StandardScaler
-scaler = StandardScaler()
-scaler.fit(X_train)
-X_train_scaled = scaler.transform(X_train)
-X_test_scaled = scaler.transform(X_test)
-logreg.fit(X_train_scaled, y_train)
-print("Test set accuracy scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
-
-

-









- -

Why should we think of reducing the dimensionality

- -

-In addition to the plot of the features, we study now also the covariance (or rather the correlation matrix). -We use also Pandas to compute the correlation matrix. -

- - -

import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.model_selection import  train_test_split 
-from sklearn.datasets import load_breast_cancer
-from sklearn.linear_model import LogisticRegression
-cancer = load_breast_cancer()
-import pandas as pd
-# Making a data frame
-cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)
-
-fig, axes = plt.subplots(15,2,figsize=(10,20))
-malignant = cancer.data[cancer.target == 0]
-benign = cancer.data[cancer.target == 1]
-ax = axes.ravel()
-
-for i in range(30):
-    _, bins = np.histogram(cancer.data[:,i], bins =50)
-    ax[i].hist(malignant[:,i], bins = bins, alpha = 0.5)
-    ax[i].hist(benign[:,i], bins = bins, alpha = 0.5)
-    ax[i].set_title(cancer.feature_names[i])
-    ax[i].set_yticks(())
-ax[0].set_xlabel("Feature magnitude")
-ax[0].set_ylabel("Frequency")
-ax[0].legend(["Malignant", "Benign"], loc ="best")
-fig.tight_layout()
-plt.show()
-
-import seaborn as sns
-correlation_matrix = cancerpd.corr().round(1)
-# use the heatmap function from seaborn to plot the correlation matrix
-# annot = True to print the values inside the square
-sns.heatmap(data=correlation_matrix, annot=True)
-plt.show()
-
-#print eigvalues of correlation matrix
-EigValues, EigVectors = np.linalg.eig(correlation_matrix)
-print(EigValues)
-
-

-In the above example we note two things. In the first plot we display -the overlap of benign and malignant tumors as functions of the various -features in the Wisconsing breast cancer data set. We see that for -some of the features we can distinguish clearly the benign and -malignant cases while for other features we cannot. This can point to -us which features may be of greater interest when we wish to classify -a benign or not benign tumour. - -

-In the second figure we have computed the so-called correlation -matrix, which in our case with thirty features becomes a \( 30\times 30 \) -matrix. - -

-We constructed this matrix using pandas via the statements -

- - -

cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)
-
-

-and then -

- - -

correlation_matrix = cancerpd.corr().round(1)
-
-

-Diagonalizing this matrix we can in turn say something about which -features are of relevance and which are not. But before we proceed we -need to define covariance and correlation matrices. This leads us to -the classical Principal Component Analysis (PCA) theorem with -applications. - -

-









- -

Basic ideas of the Principal Component Analysis (PCA)

- -

-We have a data set defined by a design/feature matrix \( \boldsymbol{X} \) (see below for its definition) - -

- -









- -

Introducing the Covariance and Correlation functions

- -

-Before we discuss the PCA theorem, we need to remind ourselves about -the definition of the covariance and the correlation function. - -

-Suppose we have defined two vectors -\( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as -$$ -\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{cov}[\boldsymbol{x},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{cov}[\boldsymbol{y},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{y},\boldsymbol{y}] \\ - \end{bmatrix}, -$$ - -where for example -$$ -\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). -$$ - -With this definition and recalling that the variance is defined as -$$ -\mathrm{var}[\boldsymbol{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2, -$$ - -we can rewrite the covariance matrix as -$$ -\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{var}[\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] & \mathrm{var}[\boldsymbol{y}] \\ - \end{bmatrix}. -$$ - -

-The covariance takes values between zero and infinity and may thus -lead to problems with loss of numerical precision for particularly -large values. It is common to scale the covariance matrix by -introducing instead the correlation matrix defined via the so-called -correlation function - -$$ -\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}. -$$ - -

-The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] -\in [-1,1] \). This avoids eventual problems with too large values. We -can then define the correlation matrix for the two vectors \( \boldsymbol{x} \) -and \( \boldsymbol{y} \) as - -$$ -\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\ - \end{bmatrix}, -$$ - -

-In the above example this is the function we constructed using pandas. - -

-









- -

Correlation Function and Design/Feature Matrix

- -

-In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression we defined the design/feature matrix \( \boldsymbol{X} \) as -$$ -\boldsymbol{X}=\begin{bmatrix} -x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ -x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ -x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ -\dots & \dots & \dots & \dots \dots & \dots \\ -x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ -x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ -\end{bmatrix}, -$$ - -with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the -entries \( n \) being the row elements. -We can rewrite the design/feature matrix in terms of its column vectors as -$$ -\boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_0 & \boldsymbol{x}_0 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix}, -$$ - -with a given vector -$$ -\boldsymbol{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}. -$$ - -

-With these definitions, we can now rewrite our \( 2\times 2 \) correaltion/covariance matrix in terms of a moe general design/feature matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \) covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i =0,1,\dots,p-1 \) -$$ -\boldsymbol{C}[\boldsymbol{x}] = \begin{bmatrix} -\mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\ -\mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\ -\mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_1] & \mathrm{var}[\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & \mathrm{var}[\boldsymbol{x}_{p-1}]\\ -\end{bmatrix}, -$$ - -and the correlation matrix -$$ -\boldsymbol{K}[\boldsymbol{x}] = \begin{bmatrix} -1 & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\ -\mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_0] & 1 & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\ -\mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & 1\\ -\end{bmatrix}, -$$ - -

-









- -

Covariance Matrix Examples

- -

-The Numpy function np.cov calculates the covariance elements using -the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have -the exact mean values. The following simple function uses the -np.vstack function which takes each vector of dimension \( 1\times n \) -and produces a \( 2\times n \) matrix \( \boldsymbol{W} \) - -$$ -\boldsymbol{W} = \begin{bmatrix} x_0 & y_0 \\ - x_1 & y_1 \\ - x_2 & y_2\\ - \dots & \dots \\ - x_{n-2} & y_{n-2}\\ - x_{n-1} & y_{n-1} & - \end{bmatrix}, -$$ - -

-which in turn is converted into into the \( 2\times 2 \) covariance matrix -\( \boldsymbol{C} \) via the Numpy function np.cov(). We note that we can also calculate -the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy -function np.mean(x). We can also extract the eigenvalues of the -covariance matrix through the np.linalg.eig() function. - -

- - -

# Importing various packages
-import numpy as np
-n = 100
-x = np.random.normal(size=n)
-print(np.mean(x))
-y = 4+3*x+np.random.normal(size=n)
-print(np.mean(y))
-W = np.vstack((x, y))
-C = np.cov(W)
-print(C)
-
-

-









- -

Correlation Matrix

- -

-The previous example can be converted into the correlation matrix by -simply scaling the matrix elements with the variances. We should also -subtract the mean values for each column. This leads to the following -code which sets up the correlations matrix for the previous example in -a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the \( 2\times 2 \) correlation matrix (since we have only two vectors). - -

- - -

import numpy as np
-n = 100
-# define two vectors                                                                                           
-x = np.random.random(size=n)
-y = 4+3*x+np.random.normal(size=n)
-#scaling the x and y vectors                                                                                   
-x = x - np.mean(x)
-y = y - np.mean(y)
-variance_x = np.sum(x@x)/n
-variance_y = np.sum(y@y)/n
-print(variance_x)
-print(variance_y)
-cov_xy = np.sum(x@y)/n
-cov_xx = np.sum(x@x)/n
-cov_yy = np.sum(y@y)/n
-C = np.zeros((2,2))
-C[0,0]= cov_xx/variance_x
-C[1,1]= cov_yy/variance_y
-C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
-C[1,0]= C[0,1]
-print(C)
-
-

-We see that the matrix elements along the diagonal are one as they -should be and that the matrix is symmetric. Furthermore, diagonalizing -this matrix we easily see that it is a positive definite matrix. - -

-The above procedure with numpy can be made more compact if we use pandas. - -

-









- -

Correlation Matrix with Pandas

- -

-We whow here how we can set up the correlation matrix using pandas, as done in this simple code -

- - -

import numpy as np
-import pandas as pd
-n = 10
-x = np.random.normal(size=n)
-x = x - np.mean(x)
-y = 4+3*x+np.random.normal(size=n)
-y = y - np.mean(y)
-X = (np.vstack((x, y))).T
-print(X)
-Xpd = pd.DataFrame(X)
-print(Xpd)
-correlation_matrix = Xpd.corr()
-print(correlation_matrix)
-
-

-We expand this model to the Franke function discussed above. - -

-









- -

Correlation Matrix with Pandas and the Franke function

- -

- - -

# Common imports
-import numpy as np
-import pandas as pd
-
-
-def FrankeFunction(x,y):
-	term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
-	term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
-	term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
-	term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
-	return term1 + term2 + term3 + term4
-
-
-def create_X(x, y, n ):
-	if len(x.shape) > 1:
-		x = np.ravel(x)
-		y = np.ravel(y)
-
-	N = len(x)
-	l = int((n+1)*(n+2)/2)		# Number of elements in beta
-	X = np.ones((N,l))
-
-	for i in range(1,n+1):
-		q = int((i)*(i+1)/2)
-		for k in range(i+1):
-			X[:,q+k] = (x**(i-k))*(y**k)
-
-	return X
-
-
-# Making meshgrid of datapoints and compute Franke's function
-n = 4
-N = 100
-x = np.sort(np.random.uniform(0, 1, N))
-y = np.sort(np.random.uniform(0, 1, N))
-z = FrankeFunction(x, y)
-X = create_X(x, y, n=n)    
-
-Xpd = pd.DataFrame(X)
-# subtract the mean values and set up the covariance matrix
-Xpd = Xpd - Xpd.mean()
-covariance_matrix = Xpd.cov()
-print(covariance_matrix)
-
-

-We note here that the covariance is zero for the first rows and -columns since all matrix elements in the design matrix were set to one -(we are fitting the function in terms of a polynomial of degree \( n \)). - -

-This means that the variance for these elements will be zero and will -cause problems when we set up the correlation matrix. We can simply -drop these elements as follows and then construct the correlation -matrix. - -

-









- -

Rewriting the Covariance and/or Correlation Matrix

- -

-We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as -$$ -\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T= \mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T]. -$$ - -

-To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \) -$$ -\boldsymbol{X}=\begin{bmatrix} -x_{00} & x_{01}\\ -x_{10} & x_{11}\\ -\end{bmatrix}=\begin{bmatrix} -\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\ -\end{bmatrix}. -$$ - -

-If we then compute the expectation value -$$ -\mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T=\begin{bmatrix} -x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\ -x_{10}x_{00}+x_{01}x_{11} & x_{10}^2+x_{11}^2\\ -\end{bmatrix}, -$$ - -which is just -$$ -\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]=\begin{bmatrix} \mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] \\ - \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] \\ - \end{bmatrix}, -$$ - -where we wrote $$\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]$$ to indicate that this the covariance of the vectors \( \boldsymbol{x} \) of the design/feature matrix \( \boldsymbol{X} \). - -

-It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). - -

-









- -

Towards the PCA theorem

- -

-We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as -$$ -\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T= \mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T]. -$$ - -Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices \( \boldsymbol{S} \). -These matrices are defined as \( \boldsymbol{S}\in {\mathbb{R}}^{p\times p} \) and obey the orthogonality requirements \( \boldsymbol{S}\boldsymbol{S}^T=\boldsymbol{S}^T\boldsymbol{S}=\boldsymbol{I} \). The matrix can be written out in terms of the column vectors \( \boldsymbol{s}_i \) as \( \boldsymbol{S}=[\boldsymbol{s}_0,\boldsymbol{s}_1,\dots,\boldsymbol{s}_{p-1}] \) and \( \boldsymbol{s}_i \in {\mathbb{R}}^{p} \). - -

-Assume also that there is a transformation \( \boldsymbol{S}\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T=\boldsymbol{C}[\boldsymbol{y}] \) such that the new matrix \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal with elements \( [\lambda_0,\lambda_1,\lambda_2,\dots,\lambda_{p-1}] \). - -

-That is we have -$$ -\boldsymbol{C}[\boldsymbol{y}] = \mathbb{E}[\boldsymbol{S}\boldsymbol{X}\boldsymbol{X}^T\boldsymbol{S}^T]=\boldsymbol{S}\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T, -$$ - -since the matrix \( \boldsymbol{S} \) is not a data dependent matrix. Multiplying with \( \boldsymbol{S}^T \) from the left we have -$$ -\boldsymbol{S}^T\boldsymbol{C}[\boldsymbol{y}] = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T, -$$ - -and since \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal we have for a given eigenvalue \( i \) of the covariance matrix that - -$$ -\boldsymbol{S}^T_i\lambda_i = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T_i. -$$ - -

-In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is -\( \lambda_0 > \lambda_1 > \dots > \lambda_{p-1} \). - -

-









- -

Classical PCA Theorem

- -

-









- -

Prof of the PCA Theorem

- -

-









- -

Getting started with PCA

- -

- - -

# Now add PCA
-from sklearn.decomposition import PCA
-pca = PCA(n_components = 2)
-pca.fit(X_train_scaled)
-
-X_pca = pca.transform(X_train_scaled)
-
-

-









- -

Principal Component Analysis

-
- -

-Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm. -First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it. - -

-The following Python code uses NumPy’s svd() function to obtain all the principal components of the -training set, then extracts the first two principal components -

- - -

X_centered = X - X.mean(axis=0)
-U, s, V = np.linalg.svd(X_centered)
-c1 = V.T[:, 0]
-c2 = V.T[:, 1]
-
-

-PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering -the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t -forget to center the data first. - -

-Once you have identified all the principal components, you can reduce the dimensionality of the dataset -down to \( d \) dimensions by projecting it onto the hyperplane defined by the first \( d \) principal components. -Selecting this hyperplane ensures that the projection will preserve as much variance as possible. -

- - -

W2 = V.T[:, :2]
-X2D = X_centered.dot(W2)
-
-

- - -

PCA and scikit-learn

- -

-Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The -following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note -that it automatically takes care of centering the data): -

- - -

from sklearn.decomposition import PCA
-pca = PCA(n_components = 2)
-X2D = pca.fit_transform(X)
-
-

-After fitting the PCA transformer to the dataset, you can access the principal components using the -components variable (note that it contains the PCs as horizontal vectors, so, for example, the first -principal component is equal to -

- - -

pca.components_.T[:, 0]).
-
-

-Another very useful piece of information is the explained variance ratio of each principal component, -available via the \( explained\_variance\_ratio \) variable. It indicates the proportion of the dataset’s -variance that lies along the axis of each principal component. -More material to come here. - -

-









- -

More on the PCA

- -

-Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to -choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%). -Unless, of course, you are reducing dimensionality for data visualization — in that case you will -generally want to reduce the dimensionality down to 2 or 3. -The following code computes PCA without reducing dimensionality, then computes the minimum number -of dimensions required to preserve 95% of the training set’s variance: -

- - -

pca = PCA()
-pca.fit(X)
-cumsum = np.cumsum(pca.explained_variance_ratio_)
-d = np.argmax(cumsum >= 0.95) + 1
-
-

-You could then set \( n\_components=d \) and run PCA again. However, there is a much better option: instead -of specifying the number of principal components you want to preserve, you can set \( n\_components \) to be -a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve: -

- - -

pca = PCA(n_components=0.95)
-X_reduced = pca.fit_transform(X)
-
-

-









- -

Incremental PCA

- -

-One problem with the preceding implementation of PCA is that it requires the whole training set to fit in -memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have -been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch -at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new -instances arrive). - -

-









- -

Randomized PCA

- -

-Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic -algorithm that quickly finds an approximation of the first d principal components. Its computational -complexity is \( O(m \times d^2)+O(d^3) \), instead of \( O(m \times n^2) + O(n^3) \), so it is dramatically faster than the -previous algorithms when \( d \) is much smaller than \( n \). - - -

- - -

-









- -

Kernel PCA

-
- -

- -

-The kernel trick is a mathematical technique that implicitly maps instances into a -very high-dimensional space (called the feature space), enabling nonlinear classification and regression -with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature -space corresponds to a complex nonlinear decision boundary in the original space. -It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear -projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at -preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a -twisted manifold. -For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an -

- - -

from sklearn.decomposition import KernelPCA
-rbf_pca = KernelPCA(n_components = 2, kernel="rbf", gamma=0.04)
-X_reduced = rbf_pca.fit_transform(X)
-
- -
- - -

-









- -

LLE

- -

-Locally Linear Embedding (LLE) is another very powerful nonlinear dimensionality reduction -(NLDR) technique. It is a Manifold Learning technique that does not rely on projections like the previous -algorithms. In a nutshell, LLE works by first measuring how each training instance linearly relates to its -closest neighbors (c.n.), and then looking for a low-dimensional representation of the training set where -these local relationships are best preserved (more details shortly). - -

-









- -

Other techniques

- -

-There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn. - -

-Here are some of the most popular: - -

- -Here are other examples where we use the DataFrame functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix -of dimensionality \( 10\times 5 \) and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations. -

- - -

import numpy as np
-import pandas as pd
-from IPython.display import display
-np.random.seed(100)
-# setting up a 10 x 5 matrix
-rows = 10
-cols = 5
-a = np.random.randn(rows,cols)
-df = pd.DataFrame(a)
-display(df)
-print(df.mean())
-print(df.std())
-display(df**2)
-
-

-Thereafter we can select specific columns only and plot final results -

- - -

df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']
-df.index = np.arange(10)
-
-display(df)
-print(df['Second'].mean() )
-print(df.info())
-print(df.describe())
-
-from pylab import plt, mpl
-plt.style.use('seaborn')
-mpl.rcParams['font.family'] = 'serif'
-
-df.cumsum().plot(lw=2.0, figsize=(10,6))
-plt.show()
-
-
-df.plot.bar(figsize=(10,6), rot=15)
-plt.show()
-
-

-We can produce a \( 4\times 4 \) matrix -

- - -

b = np.arange(16).reshape((4,4))
-print(b)
-df1 = pd.DataFrame(b)
-print(df1)
-
-

-and many other operations. - - - - -

- © 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
- - - - - - diff --git a/doc/src/DimRed/DimRed.html b/doc/src/DimRed/DimRed.html deleted file mode 100644 index f30d112ee..000000000 --- a/doc/src/DimRed/DimRed.html +++ /dev/null @@ -1,1185 +0,0 @@ - - - - - - - - -Data Analysis and Machine Learning: Preprocessing and Dimensionality Reduction - - - - - - - - - - - - - - - - - - - - - - - -

Data Analysis and Machine Learning: Preprocessing and Dimensionality Reduction

- -

- - -

-Morten Hjorth-Jensen [1, 2] -
- -

- - -

[1] Department of Physics, University of Oslo
-
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
-
-

-

Oct 22, 2019

-
-

-









- -

Reducing the number of degrees of freedom, overarching view

-
- -

- -

-Many Machine Learning problems involve thousands or even millions of -features for each training instance. Not only does this make training -extremely slow, it can also make it much harder to find a good -solution, as we will see. This problem is often referred to as the -curse of dimensionality. Fortunately, in real-world problems, it is -often possible to reduce the number of features considerably, turning -an intractable problem into a tractable one. - -

-Here we will discuss some of the most popular dimensionality reduction -techniques: the principal component analysis PCA, Kernel PCA, and -Locally Linear Embedding (LLE). Furthermore, we will start by looking -at some simple preprocessing of the data which allow us to rescale the -data. - - -

- - -

-









- -

Preprocessing our data

-
- -

- -

-Before we proceed however, we will discuss how to preprocess our -data. Till now and in connection with our previous examples we have -not met so many cases where we are too sensitive to the scaling of our -data. Normally the data may need a rescaling and/or may be sensitive -to extreme values. Scaling the data renders our inputs much more -suitable for the algorithms we want to employ. - -

-Scikit-Learn has several functions which allow us to rescale the -data, normally resulting in much better results in terms of various -accuracy scores. The StandardScaler function in Scikit-Learn -ensures that for each feature/predictor we study the mean value is -zero and the variance is one (every column in the design/feature -matrix). This scaling has the drawback that it does not ensure that -we have a particular maximum or minimum in our data set. Another -function included in Scikit-Learn is the MinMaxScaler which -ensures that all features are exactly between \( 0 \) and \( 1 \). The - -

-









- -

More preprocessing

- -

-The Normalizer scales each data -point such that the feature vector has a euclidean length of one. In other words, it -projects a data point on the circle (or sphere in the case of higher dimensions) with a -radius of 1. This means every data point is scaled by a different number (by the -inverse of it’s length). -This normalization is often used when only the direction (or angle) of the data matters, -not the length of the feature vector. - -

-The RobustScaler works similarly to the StandardScaler in that it -ensures statistical properties for each feature that guarantee that -they are on the same scale. However, the RobustScaler uses the median -and quartiles, instead of mean and variance. This makes the -RobustScaler ignore data points that are very different from the rest -(like measurement errors). These odd data points are also called -outliers, and might often lead to trouble for other scaling -techniques. - - -

- - -

-









- -

Simple preprocessing examples, Franke function and regression

- -

- - -

# Common imports
-import os
-import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-import sklearn.linear_model as skl
-from sklearn.metrics import mean_squared_error
-from sklearn.model_selection import  train_test_split
-from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer
-from sklearn.svm import SVR
-
-# 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')
-
-
-def FrankeFunction(x,y):
-	term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
-	term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
-	term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
-	term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
-	return term1 + term2 + term3 + term4
-
-
-def create_X(x, y, n ):
-	if len(x.shape) > 1:
-		x = np.ravel(x)
-		y = np.ravel(y)
-
-	N = len(x)
-	l = int((n+1)*(n+2)/2)		# Number of elements in beta
-	X = np.ones((N,l))
-
-	for i in range(1,n+1):
-		q = int((i)*(i+1)/2)
-		for k in range(i+1):
-			X[:,q+k] = (x**(i-k))*(y**k)
-
-	return X
-
-
-# Making meshgrid of datapoints and compute Franke's function
-n = 5
-N = 1000
-x = np.sort(np.random.uniform(0, 1, N))
-y = np.sort(np.random.uniform(0, 1, N))
-z = FrankeFunction(x, y)
-X = create_X(x, y, n=n)    
-# split in training and test data
-X_train, X_test, y_train, y_test = train_test_split(X,z,test_size=0.2)
-
-
-svm = SVR(gamma='auto',C=10.0)
-svm.fit(X_train, y_train)
-
-# The mean squared error and R2 score
-print("MSE before scaling: {:.2f}".format(mean_squared_error(svm.predict(X_test), y_test)))
-print("R2 score before scaling {:.2f}".format(svm.score(X_test,y_test)))
-
-scaler = StandardScaler()
-scaler.fit(X_train)
-X_train_scaled = scaler.transform(X_train)
-X_test_scaled = scaler.transform(X_test)
-
-print("Feature min values before scaling:\n {}".format(X_train.min(axis=0)))
-print("Feature max values before scaling:\n {}".format(X_train.max(axis=0)))
-
-print("Feature min values after scaling:\n {}".format(X_train_scaled.min(axis=0)))
-print("Feature max values after scaling:\n {}".format(X_train_scaled.max(axis=0)))
-
-svm = SVR(gamma='auto',C=10.0)
-svm.fit(X_train_scaled, y_train)
-
-print("MSE after  scaling: {:.2f}".format(mean_squared_error(svm.predict(X_test_scaled), y_test)))
-print("R2 score for  scaled data: {:.2f}".format(svm.score(X_test_scaled,y_test)))
-
-

-









- -

Simple preprocessing examples, breast cancer data and classification, Support Vector Machines

- -

-We show here how we can use a simple regression case on the breast -cancer data using support vector machines (SVM) as algorithm for -classification. - -

- - -

import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.model_selection import  train_test_split 
-from sklearn.datasets import load_breast_cancer
-from sklearn.svm import SVC
-cancer = load_breast_cancer()
-
-X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
-print(X_train.shape)
-print(X_test.shape)
-
-svm = SVC(C=100)
-svm.fit(X_train, y_train)
-print("Test set accuracy: {:.2f}".format(svm.score(X_test,y_test)))
-
-from sklearn.preprocessing import MinMaxScaler, StandardScaler
-scaler = MinMaxScaler()
-scaler.fit(X_train)
-X_train_scaled = scaler.transform(X_train)
-X_test_scaled = scaler.transform(X_test)
-
-print("Feature min values before scaling:\n {}".format(X_train.min(axis=0)))
-print("Feature max values before scaling:\n {}".format(X_train.max(axis=0)))
-
-print("Feature min values before scaling:\n {}".format(X_train_scaled.min(axis=0)))
-print("Feature max values before scaling:\n {}".format(X_train_scaled.max(axis=0)))
-
-
-svm.fit(X_train_scaled, y_train)
-print("Test set accuracy scaled data with Min-Max scaling: {:.2f}".format(svm.score(X_test_scaled,y_test)))
-
-scaler = StandardScaler()
-scaler.fit(X_train)
-X_train_scaled = scaler.transform(X_train)
-X_test_scaled = scaler.transform(X_test)
-
-svm.fit(X_train_scaled, y_train)
-print("Test set accuracy scaled data with Standar Scaler: {:.2f}".format(svm.score(X_test_scaled,y_test)))
-
-

-









- -

More on Cancer Data, now with Logistic Regression

- -

- - -

import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.model_selection import  train_test_split 
-from sklearn.datasets import load_breast_cancer
-from sklearn.linear_model import LogisticRegression
-cancer = load_breast_cancer()
-
-# Set up training data
-X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
-logreg = LogisticRegression()
-logreg.fit(X_train, y_train)
-print("Test set accuracy: {:.2f}".format(logreg.score(X_test,y_test)))
-
-# Scale data
-from sklearn.preprocessing import StandardScaler
-scaler = StandardScaler()
-scaler.fit(X_train)
-X_train_scaled = scaler.transform(X_train)
-X_test_scaled = scaler.transform(X_test)
-logreg.fit(X_train_scaled, y_train)
-print("Test set accuracy scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
-
-

-









- -

Why should we think of reducing the dimensionality

- -

-In addition to the plot of the features, we study now also the covariance (or rather the correlation matrix). -We use also Pandas to compute the correlation matrix. -

- - -

import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.model_selection import  train_test_split 
-from sklearn.datasets import load_breast_cancer
-from sklearn.linear_model import LogisticRegression
-cancer = load_breast_cancer()
-import pandas as pd
-# Making a data frame
-cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)
-
-fig, axes = plt.subplots(15,2,figsize=(10,20))
-malignant = cancer.data[cancer.target == 0]
-benign = cancer.data[cancer.target == 1]
-ax = axes.ravel()
-
-for i in range(30):
-    _, bins = np.histogram(cancer.data[:,i], bins =50)
-    ax[i].hist(malignant[:,i], bins = bins, alpha = 0.5)
-    ax[i].hist(benign[:,i], bins = bins, alpha = 0.5)
-    ax[i].set_title(cancer.feature_names[i])
-    ax[i].set_yticks(())
-ax[0].set_xlabel("Feature magnitude")
-ax[0].set_ylabel("Frequency")
-ax[0].legend(["Malignant", "Benign"], loc ="best")
-fig.tight_layout()
-plt.show()
-
-import seaborn as sns
-correlation_matrix = cancerpd.corr().round(1)
-# use the heatmap function from seaborn to plot the correlation matrix
-# annot = True to print the values inside the square
-sns.heatmap(data=correlation_matrix, annot=True)
-plt.show()
-
-#print eigvalues of correlation matrix
-EigValues, EigVectors = np.linalg.eig(correlation_matrix)
-print(EigValues)
-
-

-In the above example we note two things. In the first plot we display -the overlap of benign and malignant tumors as functions of the various -features in the Wisconsing breast cancer data set. We see that for -some of the features we can distinguish clearly the benign and -malignant cases while for other features we cannot. This can point to -us which features may be of greater interest when we wish to classify -a benign or not benign tumour. - -

-In the second figure we have computed the so-called correlation -matrix, which in our case with thirty features becomes a \( 30\times 30 \) -matrix. - -

-We constructed this matrix using pandas via the statements -

- - -

cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)
-
-

-and then -

- - -

correlation_matrix = cancerpd.corr().round(1)
-
-

-Diagonalizing this matrix we can in turn say something about which -features are of relevance and which are not. But before we proceed we -need to define covariance and correlation matrices. This leads us to -the classical Principal Component Analysis (PCA) theorem with -applications. - -

-









- -

Basic ideas of the Principal Component Analysis (PCA)

- -

-We have a data set defined by a design/feature matrix \( \boldsymbol{X} \) (see below for its definition) - -

- -









- -

Introducing the Covariance and Correlation functions

- -

-Before we discuss the PCA theorem, we need to remind ourselves about -the definition of the covariance and the correlation function. - -

-Suppose we have defined two vectors -\( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as -$$ -\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{cov}[\boldsymbol{x},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{cov}[\boldsymbol{y},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{y},\boldsymbol{y}] \\ - \end{bmatrix}, -$$ - -where for example -$$ -\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). -$$ - -With this definition and recalling that the variance is defined as -$$ -\mathrm{var}[\boldsymbol{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2, -$$ - -we can rewrite the covariance matrix as -$$ -\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{var}[\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] & \mathrm{var}[\boldsymbol{y}] \\ - \end{bmatrix}. -$$ - -

-The covariance takes values between zero and infinity and may thus -lead to problems with loss of numerical precision for particularly -large values. It is common to scale the covariance matrix by -introducing instead the correlation matrix defined via the so-called -correlation function - -$$ -\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}. -$$ - -

-The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] -\in [-1,1] \). This avoids eventual problems with too large values. We -can then define the correlation matrix for the two vectors \( \boldsymbol{x} \) -and \( \boldsymbol{y} \) as - -$$ -\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\ - \end{bmatrix}, -$$ - -

-In the above example this is the function we constructed using pandas. - -

-









- -

Correlation Function and Design/Feature Matrix

- -

-In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression we defined the design/feature matrix \( \boldsymbol{X} \) as -$$ -\boldsymbol{X}=\begin{bmatrix} -x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ -x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ -x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ -\dots & \dots & \dots & \dots \dots & \dots \\ -x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ -x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ -\end{bmatrix}, -$$ - -with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the -entries \( n \) being the row elements. -We can rewrite the design/feature matrix in terms of its column vectors as -$$ -\boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_0 & \boldsymbol{x}_0 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix}, -$$ - -with a given vector -$$ -\boldsymbol{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}. -$$ - -

-With these definitions, we can now rewrite our \( 2\times 2 \) correaltion/covariance matrix in terms of a moe general design/feature matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \) covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i =0,1,\dots,p-1 \) -$$ -\boldsymbol{C}[\boldsymbol{x}] = \begin{bmatrix} -\mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\ -\mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\ -\mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_1] & \mathrm{var}[\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & \mathrm{var}[\boldsymbol{x}_{p-1}]\\ -\end{bmatrix}, -$$ - -and the correlation matrix -$$ -\boldsymbol{K}[\boldsymbol{x}] = \begin{bmatrix} -1 & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\ -\mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_0] & 1 & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\ -\mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & 1\\ -\end{bmatrix}, -$$ - -

-









- -

Covariance Matrix Examples

- -

-The Numpy function np.cov calculates the covariance elements using -the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have -the exact mean values. The following simple function uses the -np.vstack function which takes each vector of dimension \( 1\times n \) -and produces a \( 2\times n \) matrix \( \boldsymbol{W} \) - -$$ -\boldsymbol{W} = \begin{bmatrix} x_0 & y_0 \\ - x_1 & y_1 \\ - x_2 & y_2\\ - \dots & \dots \\ - x_{n-2} & y_{n-2}\\ - x_{n-1} & y_{n-1} & - \end{bmatrix}, -$$ - -

-which in turn is converted into into the \( 2\times 2 \) covariance matrix -\( \boldsymbol{C} \) via the Numpy function np.cov(). We note that we can also calculate -the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy -function np.mean(x). We can also extract the eigenvalues of the -covariance matrix through the np.linalg.eig() function. - -

- - -

# Importing various packages
-import numpy as np
-n = 100
-x = np.random.normal(size=n)
-print(np.mean(x))
-y = 4+3*x+np.random.normal(size=n)
-print(np.mean(y))
-W = np.vstack((x, y))
-C = np.cov(W)
-print(C)
-
-

-









- -

Correlation Matrix

- -

-The previous example can be converted into the correlation matrix by -simply scaling the matrix elements with the variances. We should also -subtract the mean values for each column. This leads to the following -code which sets up the correlations matrix for the previous example in -a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the \( 2\times 2 \) correlation matrix (since we have only two vectors). - -

- - -

import numpy as np
-n = 100
-# define two vectors                                                                                           
-x = np.random.random(size=n)
-y = 4+3*x+np.random.normal(size=n)
-#scaling the x and y vectors                                                                                   
-x = x - np.mean(x)
-y = y - np.mean(y)
-variance_x = np.sum(x@x)/n
-variance_y = np.sum(y@y)/n
-print(variance_x)
-print(variance_y)
-cov_xy = np.sum(x@y)/n
-cov_xx = np.sum(x@x)/n
-cov_yy = np.sum(y@y)/n
-C = np.zeros((2,2))
-C[0,0]= cov_xx/variance_x
-C[1,1]= cov_yy/variance_y
-C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
-C[1,0]= C[0,1]
-print(C)
-
-

-We see that the matrix elements along the diagonal are one as they -should be and that the matrix is symmetric. Furthermore, diagonalizing -this matrix we easily see that it is a positive definite matrix. - -

-The above procedure with numpy can be made more compact if we use pandas. - -

-









- -

Correlation Matrix with Pandas

- -

-We whow here how we can set up the correlation matrix using pandas, as done in this simple code -

- - -

import numpy as np
-import pandas as pd
-n = 10
-x = np.random.normal(size=n)
-x = x - np.mean(x)
-y = 4+3*x+np.random.normal(size=n)
-y = y - np.mean(y)
-X = (np.vstack((x, y))).T
-print(X)
-Xpd = pd.DataFrame(X)
-print(Xpd)
-correlation_matrix = Xpd.corr()
-print(correlation_matrix)
-
-

-We expand this model to the Franke function discussed above. - -

-









- -

Correlation Matrix with Pandas and the Franke function

- -

- - -

# Common imports
-import numpy as np
-import pandas as pd
-
-
-def FrankeFunction(x,y):
-	term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
-	term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
-	term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
-	term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
-	return term1 + term2 + term3 + term4
-
-
-def create_X(x, y, n ):
-	if len(x.shape) > 1:
-		x = np.ravel(x)
-		y = np.ravel(y)
-
-	N = len(x)
-	l = int((n+1)*(n+2)/2)		# Number of elements in beta
-	X = np.ones((N,l))
-
-	for i in range(1,n+1):
-		q = int((i)*(i+1)/2)
-		for k in range(i+1):
-			X[:,q+k] = (x**(i-k))*(y**k)
-
-	return X
-
-
-# Making meshgrid of datapoints and compute Franke's function
-n = 4
-N = 100
-x = np.sort(np.random.uniform(0, 1, N))
-y = np.sort(np.random.uniform(0, 1, N))
-z = FrankeFunction(x, y)
-X = create_X(x, y, n=n)    
-
-Xpd = pd.DataFrame(X)
-# subtract the mean values and set up the covariance matrix
-Xpd = Xpd - Xpd.mean()
-covariance_matrix = Xpd.cov()
-print(covariance_matrix)
-
-

-We note here that the covariance is zero for the first rows and -columns since all matrix elements in the design matrix were set to one -(we are fitting the function in terms of a polynomial of degree \( n \)). - -

-This means that the variance for these elements will be zero and will -cause problems when we set up the correlation matrix. We can simply -drop these elements as follows and then construct the correlation -matrix. - -

-









- -

Rewriting the Covariance and/or Correlation Matrix

- -

-We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as -$$ -\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T= \mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T]. -$$ - -

-To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \) -$$ -\boldsymbol{X}=\begin{bmatrix} -x_{00} & x_{01}\\ -x_{10} & x_{11}\\ -\end{bmatrix}=\begin{bmatrix} -\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\ -\end{bmatrix}. -$$ - -

-If we then compute the expectation value -$$ -\mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T=\begin{bmatrix} -x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\ -x_{10}x_{00}+x_{01}x_{11} & x_{10}^2+x_{11}^2\\ -\end{bmatrix}, -$$ - -which is just -$$ -\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]=\begin{bmatrix} \mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] \\ - \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] \\ - \end{bmatrix}, -$$ - -where we wrote $$\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]$$ to indicate that this the covariance of the vectors \( \boldsymbol{x} \) of the design/feature matrix \( \boldsymbol{X} \). - -

-It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). - -

-









- -

Towards the PCA theorem

- -

-We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as -$$ -\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T= \mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T]. -$$ - -Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices \( \boldsymbol{S} \). -These matrices are defined as \( \boldsymbol{S}\in {\mathbb{R}}^{p\times p} \) and obey the orthogonality requirements \( \boldsymbol{S}\boldsymbol{S}^T=\boldsymbol{S}^T\boldsymbol{S}=\boldsymbol{I} \). The matrix can be written out in terms of the column vectors \( \boldsymbol{s}_i \) as \( \boldsymbol{S}=[\boldsymbol{s}_0,\boldsymbol{s}_1,\dots,\boldsymbol{s}_{p-1}] \) and \( \boldsymbol{s}_i \in {\mathbb{R}}^{p} \). - -

-Assume also that there is a transformation \( \boldsymbol{S}\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T=\boldsymbol{C}[\boldsymbol{y}] \) such that the new matrix \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal with elements \( [\lambda_0,\lambda_1,\lambda_2,\dots,\lambda_{p-1}] \). - -

-That is we have -$$ -\boldsymbol{C}[\boldsymbol{y}] = \mathbb{E}[\boldsymbol{S}\boldsymbol{X}\boldsymbol{X}^T\boldsymbol{S}^T]=\boldsymbol{S}\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T, -$$ - -since the matrix \( \boldsymbol{S} \) is not a data dependent matrix. Multiplying with \( \boldsymbol{S}^T \) from the left we have -$$ -\boldsymbol{S}^T\boldsymbol{C}[\boldsymbol{y}] = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T, -$$ - -and since \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal we have for a given eigenvalue \( i \) of the covariance matrix that - -$$ -\boldsymbol{S}^T_i\lambda_i = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T_i. -$$ - -

-In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is -\( \lambda_0 > \lambda_1 > \dots > \lambda_{p-1} \). - -

-









- -

Classical PCA Theorem

- -

-









- -

Prof of the PCA Theorem

- -

-









- -

Getting started with PCA

- -

- - -

# Now add PCA
-from sklearn.decomposition import PCA
-pca = PCA(n_components = 2)
-pca.fit(X_train_scaled)
-
-X_pca = pca.transform(X_train_scaled)
-
-

-









- -

Principal Component Analysis

-
- -

-Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm. -First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it. - -

-The following Python code uses NumPy’s svd() function to obtain all the principal components of the -training set, then extracts the first two principal components -

- - -

X_centered = X - X.mean(axis=0)
-U, s, V = np.linalg.svd(X_centered)
-c1 = V.T[:, 0]
-c2 = V.T[:, 1]
-
-

-PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering -the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t -forget to center the data first. - -

-Once you have identified all the principal components, you can reduce the dimensionality of the dataset -down to \( d \) dimensions by projecting it onto the hyperplane defined by the first \( d \) principal components. -Selecting this hyperplane ensures that the projection will preserve as much variance as possible. -

- - -

W2 = V.T[:, :2]
-X2D = X_centered.dot(W2)
-
-

- - -

PCA and scikit-learn

- -

-Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The -following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note -that it automatically takes care of centering the data): -

- - -

from sklearn.decomposition import PCA
-pca = PCA(n_components = 2)
-X2D = pca.fit_transform(X)
-
-

-After fitting the PCA transformer to the dataset, you can access the principal components using the -components variable (note that it contains the PCs as horizontal vectors, so, for example, the first -principal component is equal to -

- - -

pca.components_.T[:, 0]).
-
-

-Another very useful piece of information is the explained variance ratio of each principal component, -available via the \( explained\_variance\_ratio \) variable. It indicates the proportion of the dataset’s -variance that lies along the axis of each principal component. -More material to come here. - -

-









- -

More on the PCA

- -

-Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to -choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%). -Unless, of course, you are reducing dimensionality for data visualization — in that case you will -generally want to reduce the dimensionality down to 2 or 3. -The following code computes PCA without reducing dimensionality, then computes the minimum number -of dimensions required to preserve 95% of the training set’s variance: -

- - -

pca = PCA()
-pca.fit(X)
-cumsum = np.cumsum(pca.explained_variance_ratio_)
-d = np.argmax(cumsum >= 0.95) + 1
-
-

-You could then set \( n\_components=d \) and run PCA again. However, there is a much better option: instead -of specifying the number of principal components you want to preserve, you can set \( n\_components \) to be -a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve: -

- - -

pca = PCA(n_components=0.95)
-X_reduced = pca.fit_transform(X)
-
-

-









- -

Incremental PCA

- -

-One problem with the preceding implementation of PCA is that it requires the whole training set to fit in -memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have -been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch -at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new -instances arrive). - -

-









- -

Randomized PCA

- -

-Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic -algorithm that quickly finds an approximation of the first d principal components. Its computational -complexity is \( O(m \times d^2)+O(d^3) \), instead of \( O(m \times n^2) + O(n^3) \), so it is dramatically faster than the -previous algorithms when \( d \) is much smaller than \( n \). - - -

- - -

-









- -

Kernel PCA

-
- -

- -

-The kernel trick is a mathematical technique that implicitly maps instances into a -very high-dimensional space (called the feature space), enabling nonlinear classification and regression -with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature -space corresponds to a complex nonlinear decision boundary in the original space. -It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear -projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at -preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a -twisted manifold. -For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an -

- - -

from sklearn.decomposition import KernelPCA
-rbf_pca = KernelPCA(n_components = 2, kernel="rbf", gamma=0.04)
-X_reduced = rbf_pca.fit_transform(X)
-
- -
- - -

-









- -

LLE

- -

-Locally Linear Embedding (LLE) is another very powerful nonlinear dimensionality reduction -(NLDR) technique. It is a Manifold Learning technique that does not rely on projections like the previous -algorithms. In a nutshell, LLE works by first measuring how each training instance linearly relates to its -closest neighbors (c.n.), and then looking for a low-dimensional representation of the training set where -these local relationships are best preserved (more details shortly). - -

-









- -

Other techniques

- -

-There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn. - -

-Here are some of the most popular: - -

- -Here are other examples where we use the DataFrame functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix -of dimensionality \( 10\times 5 \) and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations. -

- - -

import numpy as np
-import pandas as pd
-from IPython.display import display
-np.random.seed(100)
-# setting up a 10 x 5 matrix
-rows = 10
-cols = 5
-a = np.random.randn(rows,cols)
-df = pd.DataFrame(a)
-display(df)
-print(df.mean())
-print(df.std())
-display(df**2)
-
-

-Thereafter we can select specific columns only and plot final results -

- - -

df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']
-df.index = np.arange(10)
-
-display(df)
-print(df['Second'].mean() )
-print(df.info())
-print(df.describe())
-
-from pylab import plt, mpl
-plt.style.use('seaborn')
-mpl.rcParams['font.family'] = 'serif'
-
-df.cumsum().plot(lw=2.0, figsize=(10,6))
-plt.show()
-
-
-df.plot.bar(figsize=(10,6), rot=15)
-plt.show()
-
-

-We can produce a \( 4\times 4 \) matrix -

- - -

b = np.arange(16).reshape((4,4))
-print(b)
-df1 = pd.DataFrame(b)
-print(df1)
-
-

-and many other operations. - - - - -

- © 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
- - - - - - diff --git a/doc/src/DimRed/DimRed.ipynb b/doc/src/DimRed/DimRed.ipynb deleted file mode 100644 index f2c182c39..000000000 --- a/doc/src/DimRed/DimRed.ipynb +++ /dev/null @@ -1,1353 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "# Data Analysis and Machine Learning: Preprocessing and Dimensionality Reduction\n", - "\n", - " \n", - "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", - "\n", - "Date: **Oct 22, 2019**\n", - "\n", - "Copyright 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", - "\n", - "\n", - "\n", - "\n", - "## Reducing the number of degrees of freedom, overarching view\n", - "\n", - "Many Machine Learning problems involve thousands or even millions of\n", - "features for each training instance. Not only does this make training\n", - "extremely slow, it can also make it much harder to find a good\n", - "solution, as we will see. This problem is often referred to as the\n", - "curse of dimensionality. Fortunately, in real-world problems, it is\n", - "often possible to reduce the number of features considerably, turning\n", - "an intractable problem into a tractable one.\n", - "\n", - "Here we will discuss some of the most popular dimensionality reduction\n", - "techniques: the principal component analysis PCA, Kernel PCA, and\n", - "Locally Linear Embedding (LLE). Furthermore, we will start by looking\n", - "at some simple preprocessing of the data which allow us to rescale the\n", - "data.\n", - "\n", - "\n", - "\n", - "\n", - "## Preprocessing our data\n", - "\n", - "Before we proceed however, we will discuss how to preprocess our\n", - "data. Till now and in connection with our previous examples we have\n", - "not met so many cases where we are too sensitive to the scaling of our\n", - "data. Normally the data may need a rescaling and/or may be sensitive\n", - "to extreme values. Scaling the data renders our inputs much more\n", - "suitable for the algorithms we want to employ.\n", - "\n", - "**Scikit-Learn** has several functions which allow us to rescale the\n", - "data, normally resulting in much better results in terms of various\n", - "accuracy scores. The **StandardScaler** function in **Scikit-Learn**\n", - "ensures that for each feature/predictor we study the mean value is\n", - "zero and the variance is one (every column in the design/feature\n", - "matrix). This scaling has the drawback that it does not ensure that\n", - "we have a particular maximum or minimum in our data set. Another\n", - "function included in **Scikit-Learn** is the **MinMaxScaler** which\n", - "ensures that all features are exactly between $0$ and $1$. The\n", - "\n", - "## More preprocessing\n", - "\n", - "\n", - "The **Normalizer** scales each data\n", - "point such that the feature vector has a euclidean length of one. In other words, it\n", - "projects a data point on the circle (or sphere in the case of higher dimensions) with a\n", - "radius of 1. This means every data point is scaled by a different number (by the\n", - "inverse of it’s length).\n", - "This normalization is often used when only the direction (or angle) of the data matters,\n", - "not the length of the feature vector.\n", - "\n", - "The **RobustScaler** works similarly to the StandardScaler in that it\n", - "ensures statistical properties for each feature that guarantee that\n", - "they are on the same scale. However, the RobustScaler uses the median\n", - "and quartiles, instead of mean and variance. This makes the\n", - "RobustScaler ignore data points that are very different from the rest\n", - "(like measurement errors). These odd data points are also called\n", - "outliers, and might often lead to trouble for other scaling\n", - "techniques.\n", - "\n", - "\n", - "\n", - "## Simple preprocessing examples, Franke function and regression" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "# Common imports\n", - "import os\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "import sklearn.linear_model as skl\n", - "from sklearn.metrics import mean_squared_error\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer\n", - "from sklearn.svm import SVR\n", - "\n", - "# Where to save the figures and data files\n", - "PROJECT_ROOT_DIR = \"Results\"\n", - "FIGURE_ID = \"Results/FigureFiles\"\n", - "DATA_ID = \"DataFiles/\"\n", - "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", - "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", - "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", - "\n", - "def image_path(fig_id):\n", - " return os.path.join(FIGURE_ID, fig_id)\n", - "\n", - "def data_path(dat_id):\n", - " return os.path.join(DATA_ID, dat_id)\n", - "\n", - "def save_fig(fig_id):\n", - " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", - "\n", - "\n", - "def FrankeFunction(x,y):\n", - "\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n", - "\tterm2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n", - "\tterm3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n", - "\tterm4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n", - "\treturn term1 + term2 + term3 + term4\n", - "\n", - "\n", - "def create_X(x, y, n ):\n", - "\tif len(x.shape) > 1:\n", - "\t\tx = np.ravel(x)\n", - "\t\ty = np.ravel(y)\n", - "\n", - "\tN = len(x)\n", - "\tl = int((n+1)*(n+2)/2)\t\t# Number of elements in beta\n", - "\tX = np.ones((N,l))\n", - "\n", - "\tfor i in range(1,n+1):\n", - "\t\tq = int((i)*(i+1)/2)\n", - "\t\tfor k in range(i+1):\n", - "\t\t\tX[:,q+k] = (x**(i-k))*(y**k)\n", - "\n", - "\treturn X\n", - "\n", - "\n", - "# Making meshgrid of datapoints and compute Franke's function\n", - "n = 5\n", - "N = 1000\n", - "x = np.sort(np.random.uniform(0, 1, N))\n", - "y = np.sort(np.random.uniform(0, 1, N))\n", - "z = FrankeFunction(x, y)\n", - "X = create_X(x, y, n=n) \n", - "# split in training and test data\n", - "X_train, X_test, y_train, y_test = train_test_split(X,z,test_size=0.2)\n", - "\n", - "\n", - "svm = SVR(gamma='auto',C=10.0)\n", - "svm.fit(X_train, y_train)\n", - "\n", - "# The mean squared error and R2 score\n", - "print(\"MSE before scaling: {:.2f}\".format(mean_squared_error(svm.predict(X_test), y_test)))\n", - "print(\"R2 score before scaling {:.2f}\".format(svm.score(X_test,y_test)))\n", - "\n", - "scaler = StandardScaler()\n", - "scaler.fit(X_train)\n", - "X_train_scaled = scaler.transform(X_train)\n", - "X_test_scaled = scaler.transform(X_test)\n", - "\n", - "print(\"Feature min values before scaling:\\n {}\".format(X_train.min(axis=0)))\n", - "print(\"Feature max values before scaling:\\n {}\".format(X_train.max(axis=0)))\n", - "\n", - "print(\"Feature min values after scaling:\\n {}\".format(X_train_scaled.min(axis=0)))\n", - "print(\"Feature max values after scaling:\\n {}\".format(X_train_scaled.max(axis=0)))\n", - "\n", - "svm = SVR(gamma='auto',C=10.0)\n", - "svm.fit(X_train_scaled, y_train)\n", - "\n", - "print(\"MSE after scaling: {:.2f}\".format(mean_squared_error(svm.predict(X_test_scaled), y_test)))\n", - "print(\"R2 score for scaled data: {:.2f}\".format(svm.score(X_test_scaled,y_test)))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Simple preprocessing examples, breast cancer data and classification, Support Vector Machines\n", - "\n", - "We show here how we can use a simple regression case on the breast\n", - "cancer data using support vector machines (SVM) as algorithm for\n", - "classification." - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.model_selection import train_test_split \n", - "from sklearn.datasets import load_breast_cancer\n", - "from sklearn.svm import SVC\n", - "cancer = load_breast_cancer()\n", - "\n", - "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n", - "print(X_train.shape)\n", - "print(X_test.shape)\n", - "\n", - "svm = SVC(C=100)\n", - "svm.fit(X_train, y_train)\n", - "print(\"Test set accuracy: {:.2f}\".format(svm.score(X_test,y_test)))\n", - "\n", - "from sklearn.preprocessing import MinMaxScaler, StandardScaler\n", - "scaler = MinMaxScaler()\n", - "scaler.fit(X_train)\n", - "X_train_scaled = scaler.transform(X_train)\n", - "X_test_scaled = scaler.transform(X_test)\n", - "\n", - "print(\"Feature min values before scaling:\\n {}\".format(X_train.min(axis=0)))\n", - "print(\"Feature max values before scaling:\\n {}\".format(X_train.max(axis=0)))\n", - "\n", - "print(\"Feature min values before scaling:\\n {}\".format(X_train_scaled.min(axis=0)))\n", - "print(\"Feature max values before scaling:\\n {}\".format(X_train_scaled.max(axis=0)))\n", - "\n", - "\n", - "svm.fit(X_train_scaled, y_train)\n", - "print(\"Test set accuracy scaled data with Min-Max scaling: {:.2f}\".format(svm.score(X_test_scaled,y_test)))\n", - "\n", - "scaler = StandardScaler()\n", - "scaler.fit(X_train)\n", - "X_train_scaled = scaler.transform(X_train)\n", - "X_test_scaled = scaler.transform(X_test)\n", - "\n", - "svm.fit(X_train_scaled, y_train)\n", - "print(\"Test set accuracy scaled data with Standar Scaler: {:.2f}\".format(svm.score(X_test_scaled,y_test)))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## More on Cancer Data, now with Logistic Regression" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.model_selection import train_test_split \n", - "from sklearn.datasets import load_breast_cancer\n", - "from sklearn.linear_model import LogisticRegression\n", - "cancer = load_breast_cancer()\n", - "\n", - "# Set up training data\n", - "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n", - "logreg = LogisticRegression()\n", - "logreg.fit(X_train, y_train)\n", - "print(\"Test set accuracy: {:.2f}\".format(logreg.score(X_test,y_test)))\n", - "\n", - "# Scale data\n", - "from sklearn.preprocessing import StandardScaler\n", - "scaler = StandardScaler()\n", - "scaler.fit(X_train)\n", - "X_train_scaled = scaler.transform(X_train)\n", - "X_test_scaled = scaler.transform(X_test)\n", - "logreg.fit(X_train_scaled, y_train)\n", - "print(\"Test set accuracy scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Why should we think of reducing the dimensionality\n", - "\n", - "In addition to the plot of the features, we study now also the covariance (or rather the correlation matrix).\n", - "We use also **Pandas** to compute the correlation matrix." - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.model_selection import train_test_split \n", - "from sklearn.datasets import load_breast_cancer\n", - "from sklearn.linear_model import LogisticRegression\n", - "cancer = load_breast_cancer()\n", - "import pandas as pd\n", - "# Making a data frame\n", - "cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)\n", - "\n", - "fig, axes = plt.subplots(15,2,figsize=(10,20))\n", - "malignant = cancer.data[cancer.target == 0]\n", - "benign = cancer.data[cancer.target == 1]\n", - "ax = axes.ravel()\n", - "\n", - "for i in range(30):\n", - " _, bins = np.histogram(cancer.data[:,i], bins =50)\n", - " ax[i].hist(malignant[:,i], bins = bins, alpha = 0.5)\n", - " ax[i].hist(benign[:,i], bins = bins, alpha = 0.5)\n", - " ax[i].set_title(cancer.feature_names[i])\n", - " ax[i].set_yticks(())\n", - "ax[0].set_xlabel(\"Feature magnitude\")\n", - "ax[0].set_ylabel(\"Frequency\")\n", - "ax[0].legend([\"Malignant\", \"Benign\"], loc =\"best\")\n", - "fig.tight_layout()\n", - "plt.show()\n", - "\n", - "import seaborn as sns\n", - "correlation_matrix = cancerpd.corr().round(1)\n", - "# use the heatmap function from seaborn to plot the correlation matrix\n", - "# annot = True to print the values inside the square\n", - "sns.heatmap(data=correlation_matrix, annot=True)\n", - "plt.show()\n", - "\n", - "#print eigvalues of correlation matrix\n", - "EigValues, EigVectors = np.linalg.eig(correlation_matrix)\n", - "print(EigValues)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In the above example we note two things. In the first plot we display\n", - "the overlap of benign and malignant tumors as functions of the various\n", - "features in the Wisconsing breast cancer data set. We see that for\n", - "some of the features we can distinguish clearly the benign and\n", - "malignant cases while for other features we cannot. This can point to\n", - "us which features may be of greater interest when we wish to classify\n", - "a benign or not benign tumour.\n", - "\n", - "In the second figure we have computed the so-called correlation\n", - "matrix, which in our case with thirty features becomes a $30\\times 30$\n", - "matrix.\n", - "\n", - "We constructed this matrix using **pandas** via the statements" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and then" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "correlation_matrix = cancerpd.corr().round(1)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Diagonalizing this matrix we can in turn say something about which\n", - "features are of relevance and which are not. But before we proceed we\n", - "need to define covariance and correlation matrices. This leads us to\n", - "the classical Principal Component Analysis (PCA) theorem with\n", - "applications.\n", - "\n", - "\n", - "\n", - "## Basic ideas of the Principal Component Analysis (PCA)\n", - "\n", - "We have a data set defined by a design/feature matrix $\\boldsymbol{X}$ (see below for its definition) \n", - "* Each data point is determined by $p$ extrinsic (measurement) variables\n", - "\n", - "* We may want to ask the following question: Are there fewer intrinsic variables (say $d << p$) that still approximately describe the data?\n", - "\n", - "* If so, these intrinsic variables may tell us something important and finding these intrinsic variables is what dimension reduction methods do. \n", - "\n", - "## Introducing the Covariance and Correlation functions\n", - "\n", - "Before we discuss the PCA theorem, we need to remind ourselves about\n", - "the definition of the covariance and the correlation function.\n", - "\n", - "Suppose we have defined two vectors\n", - "$\\hat{x}$ and $\\hat{y}$ with $n$ elements each. The covariance matrix $\\boldsymbol{C}$ is defined as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n", - " \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{y}] \\\\\n", - " \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where for example" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "With this definition and recalling that the variance is defined as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{var}[\\boldsymbol{x}]=\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "we can rewrite the covariance matrix as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n", - " \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] & \\mathrm{var}[\\boldsymbol{y}] \\\\\n", - " \\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The covariance takes values between zero and infinity and may thus\n", - "lead to problems with loss of numerical precision for particularly\n", - "large values. It is common to scale the covariance matrix by\n", - "introducing instead the correlation matrix defined via the so-called\n", - "correlation function" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]=\\frac{\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}]}{\\sqrt{\\mathrm{var}[\\boldsymbol{x}] \\mathrm{var}[\\boldsymbol{y}]}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The correlation function is then given by values $\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]\n", - "\\in [-1,1]$. This avoids eventual problems with too large values. We\n", - "can then define the correlation matrix for the two vectors $\\boldsymbol{x}$\n", - "and $\\boldsymbol{y}$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{K}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} 1 & \\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n", - " \\mathrm{corr}[\\boldsymbol{y},\\boldsymbol{x}] & 1 \\\\\n", - " \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In the above example this is the function we constructed using **pandas**.\n", - "\n", - "## Correlation Function and Design/Feature Matrix\n", - "\n", - "In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression we defined the design/feature matrix $\\boldsymbol{X}$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix}\n", - "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n", - "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n", - "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n", - "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n", - "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n", - "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors/features $p$ refering to the column numbers and the\n", - "entries $n$ being the row elements.\n", - "We can rewrite the design/feature matrix in terms of its column vectors as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix} \\boldsymbol{x}_0 & \\boldsymbol{x}_0 & \\boldsymbol{x}_0 & \\dots & \\dots & \\boldsymbol{x}_{p-1}\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with a given vector" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{x}_i^T = \\begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \\dots & \\dots x_{n-1,i}\\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "With these definitions, we can now rewrite our $2\\times 2$ correaltion/covariance matrix in terms of a moe general design/feature matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$. This leads to a $p\\times p$ covariance matrix for the vectors $\\boldsymbol{x}_i$ with $i =0,1,\\dots,p-1$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x}] = \\begin{bmatrix}\n", - "\\mathrm{var}[\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & \\mathrm{var}[\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", - "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", - "\\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & \\mathrm{var}[\\boldsymbol{x}_{p-1}]\\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and the correlation matrix" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{K}[\\boldsymbol{x}] = \\begin{bmatrix}\n", - "1 & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & 1 & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & 1 & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", - "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", - "\\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & 1\\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Covariance Matrix Examples\n", - "\n", - "\n", - "The Numpy function **np.cov** calculates the covariance elements using\n", - "the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have\n", - "the exact mean values. The following simple function uses the\n", - "**np.vstack** function which takes each vector of dimension $1\\times n$\n", - "and produces a $2\\times n$ matrix $\\boldsymbol{W}$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{W} = \\begin{bmatrix} x_0 & y_0 \\\\\n", - " x_1 & y_1 \\\\\n", - " x_2 & y_2\\\\\n", - " \\dots & \\dots \\\\\n", - " x_{n-2} & y_{n-2}\\\\\n", - " x_{n-1} & y_{n-1} & \n", - " \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which in turn is converted into into the $2\\times 2$ covariance matrix\n", - "$\\boldsymbol{C}$ via the Numpy function **np.cov()**. We note that we can also calculate\n", - "the mean value of each set of samples $\\boldsymbol{x}$ etc using the Numpy\n", - "function **np.mean(x)**. We can also extract the eigenvalues of the\n", - "covariance matrix through the **np.linalg.eig()** function." - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# Importing various packages\n", - "import numpy as np\n", - "n = 100\n", - "x = np.random.normal(size=n)\n", - "print(np.mean(x))\n", - "y = 4+3*x+np.random.normal(size=n)\n", - "print(np.mean(y))\n", - "W = np.vstack((x, y))\n", - "C = np.cov(W)\n", - "print(C)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Correlation Matrix\n", - "\n", - "The previous example can be converted into the correlation matrix by\n", - "simply scaling the matrix elements with the variances. We should also\n", - "subtract the mean values for each column. This leads to the following\n", - "code which sets up the correlations matrix for the previous example in\n", - "a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the $2\\times 2$ correlation matrix (since we have only two vectors)." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "n = 100\n", - "# define two vectors \n", - "x = np.random.random(size=n)\n", - "y = 4+3*x+np.random.normal(size=n)\n", - "#scaling the x and y vectors \n", - "x = x - np.mean(x)\n", - "y = y - np.mean(y)\n", - "variance_x = np.sum(x@x)/n\n", - "variance_y = np.sum(y@y)/n\n", - "print(variance_x)\n", - "print(variance_y)\n", - "cov_xy = np.sum(x@y)/n\n", - "cov_xx = np.sum(x@x)/n\n", - "cov_yy = np.sum(y@y)/n\n", - "C = np.zeros((2,2))\n", - "C[0,0]= cov_xx/variance_x\n", - "C[1,1]= cov_yy/variance_y\n", - "C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)\n", - "C[1,0]= C[0,1]\n", - "print(C)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We see that the matrix elements along the diagonal are one as they\n", - "should be and that the matrix is symmetric. Furthermore, diagonalizing\n", - "this matrix we easily see that it is a positive definite matrix.\n", - "\n", - "The above procedure with **numpy** can be made more compact if we use **pandas**.\n", - "\n", - "## Correlation Matrix with Pandas\n", - "\n", - "We whow here how we can set up the correlation matrix using **pandas**, as done in this simple code" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import pandas as pd\n", - "n = 10\n", - "x = np.random.normal(size=n)\n", - "x = x - np.mean(x)\n", - "y = 4+3*x+np.random.normal(size=n)\n", - "y = y - np.mean(y)\n", - "X = (np.vstack((x, y))).T\n", - "print(X)\n", - "Xpd = pd.DataFrame(X)\n", - "print(Xpd)\n", - "correlation_matrix = Xpd.corr()\n", - "print(correlation_matrix)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We expand this model to the Franke function discussed above.\n", - "\n", - "## Correlation Matrix with Pandas and the Franke function" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# Common imports\n", - "import numpy as np\n", - "import pandas as pd\n", - "\n", - "\n", - "def FrankeFunction(x,y):\n", - "\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n", - "\tterm2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n", - "\tterm3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n", - "\tterm4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n", - "\treturn term1 + term2 + term3 + term4\n", - "\n", - "\n", - "def create_X(x, y, n ):\n", - "\tif len(x.shape) > 1:\n", - "\t\tx = np.ravel(x)\n", - "\t\ty = np.ravel(y)\n", - "\n", - "\tN = len(x)\n", - "\tl = int((n+1)*(n+2)/2)\t\t# Number of elements in beta\n", - "\tX = np.ones((N,l))\n", - "\n", - "\tfor i in range(1,n+1):\n", - "\t\tq = int((i)*(i+1)/2)\n", - "\t\tfor k in range(i+1):\n", - "\t\t\tX[:,q+k] = (x**(i-k))*(y**k)\n", - "\n", - "\treturn X\n", - "\n", - "\n", - "# Making meshgrid of datapoints and compute Franke's function\n", - "n = 4\n", - "N = 100\n", - "x = np.sort(np.random.uniform(0, 1, N))\n", - "y = np.sort(np.random.uniform(0, 1, N))\n", - "z = FrankeFunction(x, y)\n", - "X = create_X(x, y, n=n) \n", - "\n", - "Xpd = pd.DataFrame(X)\n", - "# subtract the mean values and set up the covariance matrix\n", - "Xpd = Xpd - Xpd.mean()\n", - "covariance_matrix = Xpd.cov()\n", - "print(covariance_matrix)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We note here that the covariance is zero for the first rows and\n", - "columns since all matrix elements in the design matrix were set to one\n", - "(we are fitting the function in terms of a polynomial of degree $n$).\n", - "\n", - "This means that the variance for these elements will be zero and will\n", - "cause problems when we set up the correlation matrix. We can simply\n", - "drop these elements as follows and then construct the correlation\n", - "matrix. \n", - "\n", - "\n", - "## Rewriting the Covariance and/or Correlation Matrix\n", - "\n", - "We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\\boldsymbol{X}$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}\\boldsymbol{X}^T= \\mathbb{E}[\\boldsymbol{X}\\boldsymbol{X}^T].\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To see this let us simply look at a design matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{2\\times 2}$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix}\n", - "x_{00} & x_{01}\\\\\n", - "x_{10} & x_{11}\\\\\n", - "\\end{bmatrix}=\\begin{bmatrix}\n", - "\\boldsymbol{x}_{0} & \\boldsymbol{x}_{1}\\\\\n", - "\\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "If we then compute the expectation value" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbb{E}[\\boldsymbol{X}\\boldsymbol{X}^T] = \\frac{1}{n}\\boldsymbol{X}\\boldsymbol{X}^T=\\begin{bmatrix}\n", - "x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\\\\n", - "x_{10}x_{00}+x_{01}x_{11} & x_{10}^2+x_{11}^2\\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which is just" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]=\\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] \\\\\n", - " \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] \\\\\n", - " \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where we wrote $$\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]$$ to indicate that this the covariance of the vectors $\\boldsymbol{x}$ of the design/feature matrix $\\boldsymbol{X}$.\n", - "\n", - "It is easy to generalize this to a matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$.\n", - "\n", - "\n", - "## Towards the PCA theorem\n", - "\n", - "We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}\\boldsymbol{X}^T= \\mathbb{E}[\\boldsymbol{X}\\boldsymbol{X}^T].\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices $\\boldsymbol{S}$.\n", - "These matrices are defined as $\\boldsymbol{S}\\in {\\mathbb{R}}^{p\\times p}$ and obey the orthogonality requirements $\\boldsymbol{S}\\boldsymbol{S}^T=\\boldsymbol{S}^T\\boldsymbol{S}=\\boldsymbol{I}$. The matrix can be written out in terms of the column vectors $\\boldsymbol{s}_i$ as $\\boldsymbol{S}=[\\boldsymbol{s}_0,\\boldsymbol{s}_1,\\dots,\\boldsymbol{s}_{p-1}]$ and $\\boldsymbol{s}_i \\in {\\mathbb{R}}^{p}$.\n", - "\n", - "Assume also that there is a transformation $\\boldsymbol{S}\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S}^T=\\boldsymbol{C}[\\boldsymbol{y}]$ such that the new matrix $\\boldsymbol{C}[\\boldsymbol{y}]$ is diagonal with elements $[\\lambda_0,\\lambda_1,\\lambda_2,\\dots,\\lambda_{p-1}]$. \n", - "\n", - "That is we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{y}] = \\mathbb{E}[\\boldsymbol{S}\\boldsymbol{X}\\boldsymbol{X}^T\\boldsymbol{S}^T]=\\boldsymbol{S}\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S}^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "since the matrix $\\boldsymbol{S}$ is not a data dependent matrix. Multiplying with $\\boldsymbol{S}^T$ from the left we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{S}^T\\boldsymbol{C}[\\boldsymbol{y}] = \\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S}^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and since $\\boldsymbol{C}[\\boldsymbol{y}]$ is diagonal we have for a given eigenvalue $i$ of the covariance matrix that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{S}^T_i\\lambda_i = \\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S}^T_i.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is\n", - "$\\lambda_0 > \\lambda_1 > \\dots > \\lambda_{p-1}$. \n", - "\n", - "## Classical PCA Theorem\n", - "\n", - "\n", - "\n", - "## Prof of the PCA Theorem\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Getting started with PCA" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# Now add PCA\n", - "from sklearn.decomposition import PCA\n", - "pca = PCA(n_components = 2)\n", - "pca.fit(X_train_scaled)\n", - "\n", - "X_pca = pca.transform(X_train_scaled)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Principal Component Analysis\n", - "Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm.\n", - "First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it.\n", - "\n", - "The following Python code uses NumPy’s **svd()** function to obtain all the principal components of the\n", - "training set, then extracts the first two principal components" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "X_centered = X - X.mean(axis=0)\n", - "U, s, V = np.linalg.svd(X_centered)\n", - "c1 = V.T[:, 0]\n", - "c2 = V.T[:, 1]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering\n", - "the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t\n", - "forget to center the data first.\n", - "\n", - "Once you have identified all the principal components, you can reduce the dimensionality of the dataset\n", - "down to $d$ dimensions by projecting it onto the hyperplane defined by the first $d$ principal components.\n", - "Selecting this hyperplane ensures that the projection will preserve as much variance as possible." - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "W2 = V.T[:, :2]\n", - "X2D = X_centered.dot(W2)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "## PCA and scikit-learn\n", - "\n", - "Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The\n", - "following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note\n", - "that it automatically takes care of centering the data):" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from sklearn.decomposition import PCA\n", - "pca = PCA(n_components = 2)\n", - "X2D = pca.fit_transform(X)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "After fitting the PCA transformer to the dataset, you can access the principal components using the\n", - "components variable (note that it contains the PCs as horizontal vectors, so, for example, the first\n", - "principal component is equal to" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "pca.components_.T[:, 0])." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Another very useful piece of information is the explained variance ratio of each principal component,\n", - "available via the $explained\\_variance\\_ratio$ variable. It indicates the proportion of the dataset’s\n", - "variance that lies along the axis of each principal component. \n", - "More material to come here.\n", - "\n", - "## More on the PCA\n", - "\n", - "Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to\n", - "choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%).\n", - "Unless, of course, you are reducing dimensionality for data visualization — in that case you will\n", - "generally want to reduce the dimensionality down to 2 or 3.\n", - "The following code computes PCA without reducing dimensionality, then computes the minimum number\n", - "of dimensions required to preserve 95% of the training set’s variance:" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "pca = PCA()\n", - "pca.fit(X)\n", - "cumsum = np.cumsum(pca.explained_variance_ratio_)\n", - "d = np.argmax(cumsum >= 0.95) + 1" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You could then set $n\\_components=d$ and run PCA again. However, there is a much better option: instead\n", - "of specifying the number of principal components you want to preserve, you can set $n\\_components$ to be\n", - "a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve:" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "pca = PCA(n_components=0.95)\n", - "X_reduced = pca.fit_transform(X)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Incremental PCA\n", - "\n", - "One problem with the preceding implementation of PCA is that it requires the whole training set to fit in\n", - "memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have\n", - "been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch\n", - "at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new\n", - "instances arrive).\n", - "\n", - "## Randomized PCA\n", - "\n", - "Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic\n", - "algorithm that quickly finds an approximation of the first d principal components. Its computational\n", - "complexity is $O(m \\times d^2)+O(d^3)$, instead of $O(m \\times n^2) + O(n^3)$, so it is dramatically faster than the\n", - "previous algorithms when $d$ is much smaller than $n$.\n", - "\n", - "\n", - "\n", - "\n", - "## Kernel PCA\n", - "\n", - "The kernel trick is a mathematical technique that implicitly maps instances into a\n", - "very high-dimensional space (called the feature space), enabling nonlinear classification and regression\n", - "with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature\n", - "space corresponds to a complex nonlinear decision boundary in the original space.\n", - "It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear\n", - "projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at\n", - "preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a\n", - "twisted manifold.\n", - "For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an" - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from sklearn.decomposition import KernelPCA\n", - "rbf_pca = KernelPCA(n_components = 2, kernel=\"rbf\", gamma=0.04)\n", - "X_reduced = rbf_pca.fit_transform(X)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## LLE\n", - "\n", - "Locally Linear Embedding (LLE) is another very powerful nonlinear dimensionality reduction\n", - "(NLDR) technique. It is a Manifold Learning technique that does not rely on projections like the previous\n", - "algorithms. In a nutshell, LLE works by first measuring how each training instance linearly relates to its\n", - "closest neighbors (c.n.), and then looking for a low-dimensional representation of the training set where\n", - "these local relationships are best preserved (more details shortly). \n", - "\n", - "\n", - "\n", - "## Other techniques\n", - "\n", - "\n", - "There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn.\n", - "\n", - "Here are some of the most popular:\n", - "* **Multidimensional Scaling (MDS)** reduces dimensionality while trying to preserve the distances between the instances.\n", - "\n", - "* **Isomap** creates a graph by connecting each instance to its nearest neighbors, then reduces dimensionality while trying to preserve the geodesic distances between the instances.\n", - "\n", - "* **t-Distributed Stochastic Neighbor Embedding** (t-SNE) reduces dimensionality while trying to keep similar instances close and dissimilar instances apart. It is mostly used for visualization, in particular to visualize clusters of instances in high-dimensional space (e.g., to visualize the MNIST images in 2D).\n", - "\n", - "* Linear Discriminant Analysis (LDA) is actually a classification algorithm, but during training it learns the most discriminative axes between the classes, and these axes can then be used to define a hyperplane onto which to project the data. The benefit is that the projection will keep classes as far apart as possible, so LDA is a good technique to reduce dimensionality before running another classification algorithm such as a Support Vector Machine (SVM) classifier discussed in the SVM lectures.\n", - "\n", - "Here are other examples where we use the **DataFrame** functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix \n", - "of dimensionality $10\\times 5$ and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations." - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import pandas as pd\n", - "from IPython.display import display\n", - "np.random.seed(100)\n", - "# setting up a 10 x 5 matrix\n", - "rows = 10\n", - "cols = 5\n", - "a = np.random.randn(rows,cols)\n", - "df = pd.DataFrame(a)\n", - "display(df)\n", - "print(df.mean())\n", - "print(df.std())\n", - "display(df**2)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Thereafter we can select specific columns only and plot final results" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']\n", - "df.index = np.arange(10)\n", - "\n", - "display(df)\n", - "print(df['Second'].mean() )\n", - "print(df.info())\n", - "print(df.describe())\n", - "\n", - "from pylab import plt, mpl\n", - "plt.style.use('seaborn')\n", - "mpl.rcParams['font.family'] = 'serif'\n", - "\n", - "df.cumsum().plot(lw=2.0, figsize=(10,6))\n", - "plt.show()\n", - "\n", - "\n", - "df.plot.bar(figsize=(10,6), rot=15)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can produce a $4\\times 4$ matrix" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "b = np.arange(16).reshape((4,4))\n", - "print(b)\n", - "df1 = pd.DataFrame(b)\n", - "print(df1)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and many other operations." - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/doc/src/DimRed/DimRed.p.tex b/doc/src/DimRed/DimRed.p.tex deleted file mode 100644 index 3b38d6bd7..000000000 --- a/doc/src/DimRed/DimRed.p.tex +++ /dev/null @@ -1,1072 +0,0 @@ -%% -%% Automatically generated file from DocOnce source -%% (https://github.com/hplgit/doconce/) -%% -%% -% #ifdef PTEX2TEX_EXPLANATION -%% -%% The file follows the ptex2tex extended LaTeX format, see -%% ptex2tex: http://code.google.com/p/ptex2tex/ -%% -%% Run -%% ptex2tex myfile -%% or -%% doconce ptex2tex myfile -%% -%% to turn myfile.p.tex into an ordinary LaTeX file myfile.tex. -%% (The ptex2tex program: http://code.google.com/p/ptex2tex) -%% Many preprocess options can be added to ptex2tex or doconce ptex2tex -%% -%% ptex2tex -DMINTED myfile -%% doconce ptex2tex myfile envir=minted -%% -%% ptex2tex will typeset code environments according to a global or local -%% .ptex2tex.cfg configure file. doconce ptex2tex will typeset code -%% according to options on the command line (just type doconce ptex2tex to -%% see examples). If doconce ptex2tex has envir=minted, it enables the -%% minted style without needing -DMINTED. -% #endif - -% #define PREAMBLE - -% #ifdef PREAMBLE -%-------------------- begin preamble ---------------------- - -\documentclass[% -oneside, % oneside: electronic viewing, twoside: printing -final, % draft: marks overfull hboxes, figures with paths -10pt]{article} - -\listfiles % print all files needed to compile this document - -\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb} -\usepackage[table]{xcolor} -\usepackage{bm,ltablex,microtype} - -\usepackage[pdftex]{graphicx} - -\usepackage{ptex2tex} -% #ifdef MINTED -\usepackage{minted} -\usemintedstyle{default} -% #endif - -\usepackage[T1]{fontenc} -%\usepackage[latin1]{inputenc} -\usepackage{ucs} -\usepackage[utf8x]{inputenc} - -\usepackage{lmodern} % Latin Modern fonts derived from Computer Modern - -% Hyperlinks in PDF: -\definecolor{linkcolor}{rgb}{0,0,0.4} -\usepackage{hyperref} -\hypersetup{ - breaklinks=true, - colorlinks=true, - linkcolor=linkcolor, - urlcolor=linkcolor, - citecolor=black, - filecolor=black, - %filecolor=blue, - pdfmenubar=true, - pdftoolbar=true, - bookmarksdepth=3 % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC - } -%\hyperbaseurl{} % hyperlinks are relative to this root - -\setcounter{tocdepth}{2} % levels in table of contents - -% --- fancyhdr package for fancy headers --- -\usepackage{fancyhdr} -\fancyhf{} % sets both header and footer to nothing -\renewcommand{\headrulewidth}{0pt} -\fancyfoot[LE,RO]{\thepage} -% Ensure copyright on titlepage (article style) and chapter pages (book style) -\fancypagestyle{plain}{ - \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} -% \renewcommand{\footrulewidth}{0mm} - \renewcommand{\headrulewidth}{0mm} -} -% Ensure copyright on titlepages with \thispagestyle{empty} -\fancypagestyle{empty}{ - \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} - \renewcommand{\footrulewidth}{0mm} - \renewcommand{\headrulewidth}{0mm} -} - -\pagestyle{fancy} - - -\usepackage[framemethod=TikZ]{mdframed} - -% --- begin definitions of admonition environments --- - -% --- end of definitions of admonition environments --- - -% prevent orhpans and widows -\clubpenalty = 10000 -\widowpenalty = 10000 - -% --- end of standard preamble for documents --- - - -% insert custom LaTeX commands... - -\raggedbottom -\makeindex -\usepackage[totoc]{idxlayout} % for index in the toc -\usepackage[nottoc]{tocbibind} % for references/bibliography in the toc - -%-------------------- end preamble ---------------------- - -\begin{document} - -% matching end for #ifdef PREAMBLE -% #endif - -\newcommand{\exercisesection}[1]{\subsection*{#1}} - - -% ------------------- main content ---------------------- - - - -% ----------------- title ------------------------- - -\thispagestyle{empty} - -\begin{center} -{\LARGE\bf -\begin{spacing}{1.25} -Data Analysis and Machine Learning: Preprocessing and Dimensionality Reduction -\end{spacing} -} -\end{center} - -% ----------------- author(s) ------------------------- - -\begin{center} -{\bf Morten Hjorth-Jensen${}^{1, 2}$} \\ [0mm] -\end{center} - -\begin{center} -% List of all institutions: -\centerline{{\small ${}^1$Department of Physics, University of Oslo}} -\centerline{{\small ${}^2$Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University}} -\end{center} - -% ----------------- end author(s) ------------------------- - -% --- begin date --- -\begin{center} -Oct 22, 2019 -\end{center} -% --- end date --- - -\vspace{1cm} - - -% !split -\subsection{Reducing the number of degrees of freedom, overarching view} - -% --- begin paragraph admon --- -\paragraph{} - -Many Machine Learning problems involve thousands or even millions of -features for each training instance. Not only does this make training -extremely slow, it can also make it much harder to find a good -solution, as we will see. This problem is often referred to as the -curse of dimensionality. Fortunately, in real-world problems, it is -often possible to reduce the number of features considerably, turning -an intractable problem into a tractable one. - -Here we will discuss some of the most popular dimensionality reduction -techniques: the principal component analysis PCA, Kernel PCA, and -Locally Linear Embedding (LLE). Furthermore, we will start by looking -at some simple preprocessing of the data which allow us to rescale the -data. -% --- end paragraph admon --- - - - - -% !split -\subsection{Preprocessing our data} - -% --- begin paragraph admon --- -\paragraph{} - -Before we proceed however, we will discuss how to preprocess our -data. Till now and in connection with our previous examples we have -not met so many cases where we are too sensitive to the scaling of our -data. Normally the data may need a rescaling and/or may be sensitive -to extreme values. Scaling the data renders our inputs much more -suitable for the algorithms we want to employ. - -\textbf{Scikit-Learn} has several functions which allow us to rescale the -data, normally resulting in much better results in terms of various -accuracy scores. The \textbf{StandardScaler} function in \textbf{Scikit-Learn} -ensures that for each feature/predictor we study the mean value is -zero and the variance is one (every column in the design/feature -matrix). This scaling has the drawback that it does not ensure that -we have a particular maximum or minimum in our data set. Another -function included in \textbf{Scikit-Learn} is the \textbf{MinMaxScaler} which -ensures that all features are exactly between $0$ and $1$. The - -% !split -\subsection{More preprocessing} - - -The \textbf{Normalizer} scales each data -point such that the feature vector has a euclidean length of one. In other words, it -projects a data point on the circle (or sphere in the case of higher dimensions) with a -radius of 1. This means every data point is scaled by a different number (by the -inverse of it’s length). -This normalization is often used when only the direction (or angle) of the data matters, -not the length of the feature vector. - -The \textbf{RobustScaler} works similarly to the StandardScaler in that it -ensures statistical properties for each feature that guarantee that -they are on the same scale. However, the RobustScaler uses the median -and quartiles, instead of mean and variance. This makes the -RobustScaler ignore data points that are very different from the rest -(like measurement errors). These odd data points are also called -outliers, and might often lead to trouble for other scaling -techniques. -% --- end paragraph admon --- - - - -% !split -\subsection{Simple preprocessing examples, Franke function and regression} - -\bpycod -# Common imports -import os -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -import sklearn.linear_model as skl -from sklearn.metrics import mean_squared_error -from sklearn.model_selection import train_test_split -from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer -from sklearn.svm import SVR - -# 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') - - -def FrankeFunction(x,y): - term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2)) - term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1)) - term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2)) - term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2) - return term1 + term2 + term3 + term4 - - -def create_X(x, y, n ): - if len(x.shape) > 1: - x = np.ravel(x) - y = np.ravel(y) - - N = len(x) - l = int((n+1)*(n+2)/2) # Number of elements in beta - X = np.ones((N,l)) - - for i in range(1,n+1): - q = int((i)*(i+1)/2) - for k in range(i+1): - X[:,q+k] = (x**(i-k))*(y**k) - - return X - - -# Making meshgrid of datapoints and compute Franke's function -n = 5 -N = 1000 -x = np.sort(np.random.uniform(0, 1, N)) -y = np.sort(np.random.uniform(0, 1, N)) -z = FrankeFunction(x, y) -X = create_X(x, y, n=n) -# split in training and test data -X_train, X_test, y_train, y_test = train_test_split(X,z,test_size=0.2) - - -svm = SVR(gamma='auto',C=10.0) -svm.fit(X_train, y_train) - -# The mean squared error and R2 score -print("MSE before scaling: {:.2f}".format(mean_squared_error(svm.predict(X_test), y_test))) -print("R2 score before scaling {:.2f}".format(svm.score(X_test,y_test))) - -scaler = StandardScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) - -print("Feature min values before scaling:\n {}".format(X_train.min(axis=0))) -print("Feature max values before scaling:\n {}".format(X_train.max(axis=0))) - -print("Feature min values after scaling:\n {}".format(X_train_scaled.min(axis=0))) -print("Feature max values after scaling:\n {}".format(X_train_scaled.max(axis=0))) - -svm = SVR(gamma='auto',C=10.0) -svm.fit(X_train_scaled, y_train) - -print("MSE after scaling: {:.2f}".format(mean_squared_error(svm.predict(X_test_scaled), y_test))) -print("R2 score for scaled data: {:.2f}".format(svm.score(X_test_scaled,y_test))) - -\epycod - - - -% !split -\subsection{Simple preprocessing examples, breast cancer data and classification, Support Vector Machines} - -We show here how we can use a simple regression case on the breast -cancer data using support vector machines (SVM) as algorithm for -classification. - - -\bpycod -import matplotlib.pyplot as plt -import numpy as np -from sklearn.model_selection import train_test_split -from sklearn.datasets import load_breast_cancer -from sklearn.svm import SVC -cancer = load_breast_cancer() - -X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0) -print(X_train.shape) -print(X_test.shape) - -svm = SVC(C=100) -svm.fit(X_train, y_train) -print("Test set accuracy: {:.2f}".format(svm.score(X_test,y_test))) - -from sklearn.preprocessing import MinMaxScaler, StandardScaler -scaler = MinMaxScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) - -print("Feature min values before scaling:\n {}".format(X_train.min(axis=0))) -print("Feature max values before scaling:\n {}".format(X_train.max(axis=0))) - -print("Feature min values before scaling:\n {}".format(X_train_scaled.min(axis=0))) -print("Feature max values before scaling:\n {}".format(X_train_scaled.max(axis=0))) - - -svm.fit(X_train_scaled, y_train) -print("Test set accuracy scaled data with Min-Max scaling: {:.2f}".format(svm.score(X_test_scaled,y_test))) - -scaler = StandardScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) - -svm.fit(X_train_scaled, y_train) -print("Test set accuracy scaled data with Standar Scaler: {:.2f}".format(svm.score(X_test_scaled,y_test))) - -\epycod - -% !split -\subsection{More on Cancer Data, now with Logistic Regression} - - -\bpycod -import matplotlib.pyplot as plt -import numpy as np -from sklearn.model_selection import train_test_split -from sklearn.datasets import load_breast_cancer -from sklearn.linear_model import LogisticRegression -cancer = load_breast_cancer() - -# Set up training data -X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0) -logreg = LogisticRegression() -logreg.fit(X_train, y_train) -print("Test set accuracy: {:.2f}".format(logreg.score(X_test,y_test))) - -# Scale data -from sklearn.preprocessing import StandardScaler -scaler = StandardScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) -logreg.fit(X_train_scaled, y_train) -print("Test set accuracy scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) - -\epycod - - - - -% !split -\subsection{Why should we think of reducing the dimensionality} - -In addition to the plot of the features, we study now also the covariance (or rather the correlation matrix). -We use also \textbf{Pandas} to compute the correlation matrix. -\bpycod -import matplotlib.pyplot as plt -import numpy as np -from sklearn.model_selection import train_test_split -from sklearn.datasets import load_breast_cancer -from sklearn.linear_model import LogisticRegression -cancer = load_breast_cancer() -import pandas as pd -# Making a data frame -cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names) - -fig, axes = plt.subplots(15,2,figsize=(10,20)) -malignant = cancer.data[cancer.target == 0] -benign = cancer.data[cancer.target == 1] -ax = axes.ravel() - -for i in range(30): - _, bins = np.histogram(cancer.data[:,i], bins =50) - ax[i].hist(malignant[:,i], bins = bins, alpha = 0.5) - ax[i].hist(benign[:,i], bins = bins, alpha = 0.5) - ax[i].set_title(cancer.feature_names[i]) - ax[i].set_yticks(()) -ax[0].set_xlabel("Feature magnitude") -ax[0].set_ylabel("Frequency") -ax[0].legend(["Malignant", "Benign"], loc ="best") -fig.tight_layout() -plt.show() - -import seaborn as sns -correlation_matrix = cancerpd.corr().round(1) -# use the heatmap function from seaborn to plot the correlation matrix -# annot = True to print the values inside the square -sns.heatmap(data=correlation_matrix, annot=True) -plt.show() - -#print eigvalues of correlation matrix -EigValues, EigVectors = np.linalg.eig(correlation_matrix) -print(EigValues) -\epycod - -In the above example we note two things. In the first plot we display -the overlap of benign and malignant tumors as functions of the various -features in the Wisconsing breast cancer data set. We see that for -some of the features we can distinguish clearly the benign and -malignant cases while for other features we cannot. This can point to -us which features may be of greater interest when we wish to classify -a benign or not benign tumour. - -In the second figure we have computed the so-called correlation -matrix, which in our case with thirty features becomes a $30\times 30$ -matrix. - -We constructed this matrix using \textbf{pandas} via the statements -\bpycod -cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names) -\epycod -and then -\bpycod -correlation_matrix = cancerpd.corr().round(1) -\epycod - -Diagonalizing this matrix we can in turn say something about which -features are of relevance and which are not. But before we proceed we -need to define covariance and correlation matrices. This leads us to -the classical Principal Component Analysis (PCA) theorem with -applications. - - - -% !split -\subsection{Basic ideas of the Principal Component Analysis (PCA)} - -We have a data set defined by a design/feature matrix $\bm{X}$ (see below for its definition) -\begin{itemize} -\item Each data point is determined by $p$ extrinsic (measurement) variables - -\item We may want to ask the following question: Are there fewer intrinsic variables (say $d << p$) that still approximately describe the data? - -\item If so, these intrinsic variables may tell us something important and finding these intrinsic variables is what dimension reduction methods do. -\end{itemize} - -\noindent -% !split -\subsection{Introducing the Covariance and Correlation functions} - -Before we discuss the PCA theorem, we need to remind ourselves about -the definition of the covariance and the correlation function. - -Suppose we have defined two vectors -$\hat{x}$ and $\hat{y}$ with $n$ elements each. The covariance matrix $\bm{C}$ is defined as -\[ -\bm{C}[\bm{x},\bm{y}] = \begin{bmatrix} \mathrm{cov}[\bm{x},\bm{x}] & \mathrm{cov}[\bm{x},\bm{y}] \\ - \mathrm{cov}[\bm{y},\bm{x}] & \mathrm{cov}[\bm{y},\bm{y}] \\ - \end{bmatrix}, -\] -where for example -\[ -\mathrm{cov}[\bm{x},\bm{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). -\] -With this definition and recalling that the variance is defined as -\[ -\mathrm{var}[\bm{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2, -\] -we can rewrite the covariance matrix as -\[ -\bm{C}[\bm{x},\bm{y}] = \begin{bmatrix} \mathrm{var}[\bm{x}] & \mathrm{cov}[\bm{x},\bm{y}] \\ - \mathrm{cov}[\bm{x},\bm{y}] & \mathrm{var}[\bm{y}] \\ - \end{bmatrix}. -\] - -The covariance takes values between zero and infinity and may thus -lead to problems with loss of numerical precision for particularly -large values. It is common to scale the covariance matrix by -introducing instead the correlation matrix defined via the so-called -correlation function - -\[ -\mathrm{corr}[\bm{x},\bm{y}]=\frac{\mathrm{cov}[\bm{x},\bm{y}]}{\sqrt{\mathrm{var}[\bm{x}] \mathrm{var}[\bm{y}]}}. -\] - -The correlation function is then given by values $\mathrm{corr}[\bm{x},\bm{y}] -\in [-1,1]$. This avoids eventual problems with too large values. We -can then define the correlation matrix for the two vectors $\bm{x}$ -and $\bm{y}$ as - -\[ -\bm{K}[\bm{x},\bm{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\bm{x},\bm{y}] \\ - \mathrm{corr}[\bm{y},\bm{x}] & 1 \\ - \end{bmatrix}, -\] - -In the above example this is the function we constructed using \textbf{pandas}. - -% !split -\subsection{Correlation Function and Design/Feature Matrix} - -In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression we defined the design/feature matrix $\bm{X}$ as -\[ -\bm{X}=\begin{bmatrix} -x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ -x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ -x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ -\dots & \dots & \dots & \dots \dots & \dots \\ -x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ -x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ -\end{bmatrix}, -\] -with $\bm{X}\in {\mathbb{R}}^{n\times p}$, with the predictors/features $p$ refering to the column numbers and the -entries $n$ being the row elements. -We can rewrite the design/feature matrix in terms of its column vectors as -\[ -\bm{X}=\begin{bmatrix} \bm{x}_0 & \bm{x}_0 & \bm{x}_0 & \dots & \dots & \bm{x}_{p-1}\end{bmatrix}, -\] -with a given vector -\[ -\bm{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}. -\] - -With these definitions, we can now rewrite our $2\times 2$ correaltion/covariance matrix in terms of a moe general design/feature matrix $\bm{X}\in {\mathbb{R}}^{n\times p}$. This leads to a $p\times p$ covariance matrix for the vectors $\bm{x}_i$ with $i =0,1,\dots,p-1$ -\[ -\bm{C}[\bm{x}] = \begin{bmatrix} -\mathrm{var}[\bm{x}_0] & \mathrm{cov}[\bm{x}_0,\bm{x}_1] & \mathrm{cov}[\bm{x}_0,\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_0,\bm{x}_{p-1}]\\ -\mathrm{cov}[\bm{x}_1,\bm{x}_0] & \mathrm{var}[\bm{x}_1] & \mathrm{cov}[\bm{x}_1,\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_1,\bm{x}_{p-1}]\\ -\mathrm{cov}[\bm{x}_2,\bm{x}_0] & \mathrm{cov}[\bm{x}_2,\bm{x}_1] & \mathrm{var}[\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_2,\bm{x}_{p-1}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\mathrm{cov}[\bm{x}_{p-1},\bm{x}_0] & \mathrm{cov}[\bm{x}_{p-1},\bm{x}_1] & \mathrm{cov}[\bm{x}_{p-1},\bm{x}_{2}] & \dots & \dots & \mathrm{var}[\bm{x}_{p-1}]\\ -\end{bmatrix}, -\] -and the correlation matrix -\[ -\bm{K}[\bm{x}] = \begin{bmatrix} -1 & \mathrm{corr}[\bm{x}_0,\bm{x}_1] & \mathrm{corr}[\bm{x}_0,\bm{x}_2] & \dots & \dots & \mathrm{corr}[\bm{x}_0,\bm{x}_{p-1}]\\ -\mathrm{corr}[\bm{x}_1,\bm{x}_0] & 1 & \mathrm{corr}[\bm{x}_1,\bm{x}_2] & \dots & \dots & \mathrm{corr}[\bm{x}_1,\bm{x}_{p-1}]\\ -\mathrm{corr}[\bm{x}_2,\bm{x}_0] & \mathrm{corr}[\bm{x}_2,\bm{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\bm{x}_2,\bm{x}_{p-1}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\mathrm{corr}[\bm{x}_{p-1},\bm{x}_0] & \mathrm{corr}[\bm{x}_{p-1},\bm{x}_1] & \mathrm{corr}[\bm{x}_{p-1},\bm{x}_{2}] & \dots & \dots & 1\\ -\end{bmatrix}, -\] - - -% !split -\subsection{Covariance Matrix Examples} - - -The Numpy function \textbf{np.cov} calculates the covariance elements using -the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have -the exact mean values. The following simple function uses the -\textbf{np.vstack} function which takes each vector of dimension $1\times n$ -and produces a $2\times n$ matrix $\bm{W}$ - - -\[ -\bm{W} = \begin{bmatrix} x_0 & y_0 \\ - x_1 & y_1 \\ - x_2 & y_2\\ - \dots & \dots \\ - x_{n-2} & y_{n-2}\\ - x_{n-1} & y_{n-1} & - \end{bmatrix}, -\] - -which in turn is converted into into the $2\times 2$ covariance matrix -$\bm{C}$ via the Numpy function \textbf{np.cov()}. We note that we can also calculate -the mean value of each set of samples $\bm{x}$ etc using the Numpy -function \textbf{np.mean(x)}. We can also extract the eigenvalues of the -covariance matrix through the \textbf{np.linalg.eig()} function. - -\bpycod -# Importing various packages -import numpy as np -n = 100 -x = np.random.normal(size=n) -print(np.mean(x)) -y = 4+3*x+np.random.normal(size=n) -print(np.mean(y)) -W = np.vstack((x, y)) -C = np.cov(W) -print(C) -\epycod - -% !split -\subsection{Correlation Matrix} - -The previous example can be converted into the correlation matrix by -simply scaling the matrix elements with the variances. We should also -subtract the mean values for each column. This leads to the following -code which sets up the correlations matrix for the previous example in -a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the $2\times 2$ correlation matrix (since we have only two vectors). - -\bpycod -import numpy as np -n = 100 -# define two vectors -x = np.random.random(size=n) -y = 4+3*x+np.random.normal(size=n) -#scaling the x and y vectors -x = x - np.mean(x) -y = y - np.mean(y) -variance_x = np.sum(x@x)/n -variance_y = np.sum(y@y)/n -print(variance_x) -print(variance_y) -cov_xy = np.sum(x@y)/n -cov_xx = np.sum(x@x)/n -cov_yy = np.sum(y@y)/n -C = np.zeros((2,2)) -C[0,0]= cov_xx/variance_x -C[1,1]= cov_yy/variance_y -C[0,1]= cov_xy/np.sqrt(variance_y*variance_x) -C[1,0]= C[0,1] -print(C) -\epycod - -We see that the matrix elements along the diagonal are one as they -should be and that the matrix is symmetric. Furthermore, diagonalizing -this matrix we easily see that it is a positive definite matrix. - -The above procedure with \textbf{numpy} can be made more compact if we use \textbf{pandas}. - -% !split -\subsection{Correlation Matrix with Pandas} - -We whow here how we can set up the correlation matrix using \textbf{pandas}, as done in this simple code -\bpycod -import numpy as np -import pandas as pd -n = 10 -x = np.random.normal(size=n) -x = x - np.mean(x) -y = 4+3*x+np.random.normal(size=n) -y = y - np.mean(y) -X = (np.vstack((x, y))).T -print(X) -Xpd = pd.DataFrame(X) -print(Xpd) -correlation_matrix = Xpd.corr() -print(correlation_matrix) -\epycod - - -We expand this model to the Franke function discussed above. - -% !split -\subsection{Correlation Matrix with Pandas and the Franke function} - -\bpycod -# Common imports -import numpy as np -import pandas as pd - - -def FrankeFunction(x,y): - term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2)) - term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1)) - term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2)) - term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2) - return term1 + term2 + term3 + term4 - - -def create_X(x, y, n ): - if len(x.shape) > 1: - x = np.ravel(x) - y = np.ravel(y) - - N = len(x) - l = int((n+1)*(n+2)/2) # Number of elements in beta - X = np.ones((N,l)) - - for i in range(1,n+1): - q = int((i)*(i+1)/2) - for k in range(i+1): - X[:,q+k] = (x**(i-k))*(y**k) - - return X - - -# Making meshgrid of datapoints and compute Franke's function -n = 4 -N = 100 -x = np.sort(np.random.uniform(0, 1, N)) -y = np.sort(np.random.uniform(0, 1, N)) -z = FrankeFunction(x, y) -X = create_X(x, y, n=n) - -Xpd = pd.DataFrame(X) -# subtract the mean values and set up the covariance matrix -Xpd = Xpd - Xpd.mean() -covariance_matrix = Xpd.cov() -print(covariance_matrix) -\epycod - -We note here that the covariance is zero for the first rows and -columns since all matrix elements in the design matrix were set to one -(we are fitting the function in terms of a polynomial of degree $n$). - -This means that the variance for these elements will be zero and will -cause problems when we set up the correlation matrix. We can simply -drop these elements as follows and then construct the correlation -matrix. - - -% !split -\subsection{Rewriting the Covariance and/or Correlation Matrix} - -We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\bm{X}$ as -\[ -\bm{C}[\bm{x}] = \frac{1}{n}\bm{X}\bm{X}^T= \mathbb{E}[\bm{X}\bm{X}^T]. -\] - -To see this let us simply look at a design matrix $\bm{X}\in {\mathbb{R}}^{2\times 2}$ -\[ -\bm{X}=\begin{bmatrix} -x_{00} & x_{01}\\ -x_{10} & x_{11}\\ -\end{bmatrix}=\begin{bmatrix} -\bm{x}_{0} & \bm{x}_{1}\\ -\end{bmatrix}. -\] - -If we then compute the expectation value -\[ -\mathbb{E}[\bm{X}\bm{X}^T] = \frac{1}{n}\bm{X}\bm{X}^T=\begin{bmatrix} -x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\ -x_{10}x_{00}+x_{01}x_{11} & x_{10}^2+x_{11}^2\\ -\end{bmatrix}, -\] -which is just -\[ -\bm{C}[\bm{x}_0,\bm{x}_1] = \bm{C}[\bm{x}]=\begin{bmatrix} \mathrm{var}[\bm{x}_0] & \mathrm{cov}[\bm{x}_0,\bm{x}_1] \\ - \mathrm{cov}[\bm{x}_1,\bm{x}_0] & \mathrm{var}[\bm{x}_1] \\ - \end{bmatrix}, -\] -where we wrote $$\bm{C}[\bm{x}_0,\bm{x}_1] = \bm{C}[\bm{x}]$$ to indicate that this the covariance of the vectors $\bm{x}$ of the design/feature matrix $\bm{X}$. - -It is easy to generalize this to a matrix $\bm{X}\in {\mathbb{R}}^{n\times p}$. - - -% !split -\subsection{Towards the PCA theorem} - -We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as -\[ -\bm{C}[\bm{x}] = \frac{1}{n}\bm{X}\bm{X}^T= \mathbb{E}[\bm{X}\bm{X}^T]. -\] -Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices $\bm{S}$. -These matrices are defined as $\bm{S}\in {\mathbb{R}}^{p\times p}$ and obey the orthogonality requirements $\bm{S}\bm{S}^T=\bm{S}^T\bm{S}=\bm{I}$. The matrix can be written out in terms of the column vectors $\bm{s}_i$ as $\bm{S}=[\bm{s}_0,\bm{s}_1,\dots,\bm{s}_{p-1}]$ and $\bm{s}_i \in {\mathbb{R}}^{p}$. - -Assume also that there is a transformation $\bm{S}\bm{C}[\bm{x}]\bm{S}^T=\bm{C}[\bm{y}]$ such that the new matrix $\bm{C}[\bm{y}]$ is diagonal with elements $[\lambda_0,\lambda_1,\lambda_2,\dots,\lambda_{p-1}]$. - -That is we have -\[ -\bm{C}[\bm{y}] = \mathbb{E}[\bm{S}\bm{X}\bm{X}^T\bm{S}^T]=\bm{S}\bm{C}[\bm{x}]\bm{S}^T, -\] -since the matrix $\bm{S}$ is not a data dependent matrix. Multiplying with $\bm{S}^T$ from the left we have -\[ -\bm{S}^T\bm{C}[\bm{y}] = \bm{C}[\bm{x}]\bm{S}^T, -\] -and since $\bm{C}[\bm{y}]$ is diagonal we have for a given eigenvalue $i$ of the covariance matrix that - -\[ -\bm{S}^T_i\lambda_i = \bm{C}[\bm{x}]\bm{S}^T_i. -\] - -In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is -$\lambda_0 > \lambda_1 > \dots > \lambda_{p-1}$. - -% !split -\subsection{Classical PCA Theorem} - - - -% !split -\subsection{Prof of the PCA Theorem} - - - - - - -% !split -\subsection{Getting started with PCA} - - -\bpycod -# Now add PCA -from sklearn.decomposition import PCA -pca = PCA(n_components = 2) -pca.fit(X_train_scaled) - -X_pca = pca.transform(X_train_scaled) -\epycod - - - -% !split -\subsection{Principal Component Analysis} - -% --- begin paragraph admon --- -\paragraph{} -Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm. -First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it. - -The following Python code uses NumPy’s \textbf{svd()} function to obtain all the principal components of the -training set, then extracts the first two principal components -\bpycod -X_centered = X - X.mean(axis=0) -U, s, V = np.linalg.svd(X_centered) -c1 = V.T[:, 0] -c2 = V.T[:, 1] -\epycod - -PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering -the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t -forget to center the data first. - -Once you have identified all the principal components, you can reduce the dimensionality of the dataset -down to $d$ dimensions by projecting it onto the hyperplane defined by the first $d$ principal components. -Selecting this hyperplane ensures that the projection will preserve as much variance as possible. -\bpycod -W2 = V.T[:, :2] -X2D = X_centered.dot(W2) -\epycod - -% !split -\subsection{PCA and scikit-learn} - -Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The -following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note -that it automatically takes care of centering the data): -\bpycod -from sklearn.decomposition import PCA -pca = PCA(n_components = 2) -X2D = pca.fit_transform(X) -\epycod -After fitting the PCA transformer to the dataset, you can access the principal components using the -components variable (note that it contains the PCs as horizontal vectors, so, for example, the first -principal component is equal to -\bpycod -pca.components_.T[:, 0]). -\epycod -Another very useful piece of information is the explained variance ratio of each principal component, -available via the $explained\_variance\_ratio$ variable. It indicates the proportion of the dataset’s -variance that lies along the axis of each principal component. -More material to come here. - -% !split -\subsection{More on the PCA} - -Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to -choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95\%). -Unless, of course, you are reducing dimensionality for data visualization — in that case you will -generally want to reduce the dimensionality down to 2 or 3. -The following code computes PCA without reducing dimensionality, then computes the minimum number -of dimensions required to preserve 95\% of the training set’s variance: -\bpycod -pca = PCA() -pca.fit(X) -cumsum = np.cumsum(pca.explained_variance_ratio_) -d = np.argmax(cumsum >= 0.95) + 1 -\epycod -You could then set $n\_components=d$ and run PCA again. However, there is a much better option: instead -of specifying the number of principal components you want to preserve, you can set $n\_components$ to be -a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve: -\bpycod -pca = PCA(n_components=0.95) -X_reduced = pca.fit_transform(X) -\epycod - -% !split -\subsection{Incremental PCA} - -One problem with the preceding implementation of PCA is that it requires the whole training set to fit in -memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have -been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch -at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new -instances arrive). - -% !split -\subsection{Randomized PCA} - -Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic -algorithm that quickly finds an approximation of the first d principal components. Its computational -complexity is $O(m \times d^2)+O(d^3)$, instead of $O(m \times n^2) + O(n^3)$, so it is dramatically faster than the -previous algorithms when $d$ is much smaller than $n$. -% --- end paragraph admon --- - - - - -% !split -\subsection{Kernel PCA} - -% --- begin paragraph admon --- -\paragraph{} - -The kernel trick is a mathematical technique that implicitly maps instances into a -very high-dimensional space (called the feature space), enabling nonlinear classification and regression -with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature -space corresponds to a complex nonlinear decision boundary in the original space. -It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear -projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at -preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a -twisted manifold. -For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an -\bpycod -from sklearn.decomposition import KernelPCA -rbf_pca = KernelPCA(n_components = 2, kernel="rbf", gamma=0.04) -X_reduced = rbf_pca.fit_transform(X) -\epycod -% --- end paragraph admon --- - - - - -% !split -\subsection{LLE} - -Locally Linear Embedding (LLE) is another very powerful nonlinear dimensionality reduction -(NLDR) technique. It is a Manifold Learning technique that does not rely on projections like the previous -algorithms. In a nutshell, LLE works by first measuring how each training instance linearly relates to its -closest neighbors (c.n.), and then looking for a low-dimensional representation of the training set where -these local relationships are best preserved (more details shortly). - - - -% !split -\subsection{Other techniques} - - -There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn. - -Here are some of the most popular: -\begin{itemize} -\item \textbf{Multidimensional Scaling (MDS)} reduces dimensionality while trying to preserve the distances between the instances. - -\item \textbf{Isomap} creates a graph by connecting each instance to its nearest neighbors, then reduces dimensionality while trying to preserve the geodesic distances between the instances. - -\item \textbf{t-Distributed Stochastic Neighbor Embedding} (t-SNE) reduces dimensionality while trying to keep similar instances close and dissimilar instances apart. It is mostly used for visualization, in particular to visualize clusters of instances in high-dimensional space (e.g., to visualize the MNIST images in 2D). - -\item Linear Discriminant Analysis (LDA) is actually a classification algorithm, but during training it learns the most discriminative axes between the classes, and these axes can then be used to define a hyperplane onto which to project the data. The benefit is that the projection will keep classes as far apart as possible, so LDA is a good technique to reduce dimensionality before running another classification algorithm such as a Support Vector Machine (SVM) classifier discussed in the SVM lectures. -\end{itemize} - -\noindent -Here are other examples where we use the \textbf{DataFrame} functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix -of dimensionality $10\times 5$ and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations. -\bpycod -import numpy as np -import pandas as pd -from IPython.display import display -np.random.seed(100) -# setting up a 10 x 5 matrix -rows = 10 -cols = 5 -a = np.random.randn(rows,cols) -df = pd.DataFrame(a) -display(df) -print(df.mean()) -print(df.std()) -display(df**2) -\epycod - -Thereafter we can select specific columns only and plot final results -\bpycod -df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth'] -df.index = np.arange(10) - -display(df) -print(df['Second'].mean() ) -print(df.info()) -print(df.describe()) - -from pylab import plt, mpl -plt.style.use('seaborn') -mpl.rcParams['font.family'] = 'serif' - -df.cumsum().plot(lw=2.0, figsize=(10,6)) -plt.show() - - -df.plot.bar(figsize=(10,6), rot=15) -plt.show() -\epycod -We can produce a $4\times 4$ matrix -\bpycod -b = np.arange(16).reshape((4,4)) -print(b) -df1 = pd.DataFrame(b) -print(df1) -\epycod -and many other operations. - - -% ------------------- end of main content --------------- - -% #ifdef PREAMBLE -\end{document} -% #endif - diff --git a/doc/src/DimRed/DimRed.tex b/doc/src/DimRed/DimRed.tex deleted file mode 100644 index a10b4ab77..000000000 --- a/doc/src/DimRed/DimRed.tex +++ /dev/null @@ -1,1042 +0,0 @@ -%% -%% Automatically generated file from DocOnce source -%% (https://github.com/hplgit/doconce/) -%% -%% - - -%-------------------- begin preamble ---------------------- - -\documentclass[% -oneside, % oneside: electronic viewing, twoside: printing -final, % draft: marks overfull hboxes, figures with paths -10pt]{article} - -\listfiles % print all files needed to compile this document - -\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb} -\usepackage[table]{xcolor} -\usepackage{bm,ltablex,microtype} - -\usepackage[pdftex]{graphicx} - -\usepackage{fancyvrb} % packages needed for verbatim environments -\usepackage{minted} -\usemintedstyle{default} - -\usepackage[T1]{fontenc} -%\usepackage[latin1]{inputenc} -\usepackage{ucs} -\usepackage[utf8x]{inputenc} - -\usepackage{lmodern} % Latin Modern fonts derived from Computer Modern - -% Hyperlinks in PDF: -\definecolor{linkcolor}{rgb}{0,0,0.4} -\usepackage{hyperref} -\hypersetup{ - breaklinks=true, - colorlinks=true, - linkcolor=linkcolor, - urlcolor=linkcolor, - citecolor=black, - filecolor=black, - %filecolor=blue, - pdfmenubar=true, - pdftoolbar=true, - bookmarksdepth=3 % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC - } -%\hyperbaseurl{} % hyperlinks are relative to this root - -\setcounter{tocdepth}{2} % levels in table of contents - -% --- fancyhdr package for fancy headers --- -\usepackage{fancyhdr} -\fancyhf{} % sets both header and footer to nothing -\renewcommand{\headrulewidth}{0pt} -\fancyfoot[LE,RO]{\thepage} -% Ensure copyright on titlepage (article style) and chapter pages (book style) -\fancypagestyle{plain}{ - \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} -% \renewcommand{\footrulewidth}{0mm} - \renewcommand{\headrulewidth}{0mm} -} -% Ensure copyright on titlepages with \thispagestyle{empty} -\fancypagestyle{empty}{ - \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license}} - \renewcommand{\footrulewidth}{0mm} - \renewcommand{\headrulewidth}{0mm} -} - -\pagestyle{fancy} - - -\usepackage[framemethod=TikZ]{mdframed} - -% --- begin definitions of admonition environments --- - -% --- end of definitions of admonition environments --- - -% prevent orhpans and widows -\clubpenalty = 10000 -\widowpenalty = 10000 - -% --- end of standard preamble for documents --- - - -% insert custom LaTeX commands... - -\raggedbottom -\makeindex -\usepackage[totoc]{idxlayout} % for index in the toc -\usepackage[nottoc]{tocbibind} % for references/bibliography in the toc - -%-------------------- end preamble ---------------------- - -\begin{document} - -% matching end for #ifdef PREAMBLE - -\newcommand{\exercisesection}[1]{\subsection*{#1}} - - -% ------------------- main content ---------------------- - - - -% ----------------- title ------------------------- - -\thispagestyle{empty} - -\begin{center} -{\LARGE\bf -\begin{spacing}{1.25} -Data Analysis and Machine Learning: Preprocessing and Dimensionality Reduction -\end{spacing} -} -\end{center} - -% ----------------- author(s) ------------------------- - -\begin{center} -{\bf Morten Hjorth-Jensen${}^{1, 2}$} \\ [0mm] -\end{center} - -\begin{center} -% List of all institutions: -\centerline{{\small ${}^1$Department of Physics, University of Oslo}} -\centerline{{\small ${}^2$Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University}} -\end{center} - -% ----------------- end author(s) ------------------------- - -% --- begin date --- -\begin{center} -Oct 22, 2019 -\end{center} -% --- end date --- - -\vspace{1cm} - - -% !split -\subsection*{Reducing the number of degrees of freedom, overarching view} - -% --- begin paragraph admon --- -\paragraph{} - -Many Machine Learning problems involve thousands or even millions of -features for each training instance. Not only does this make training -extremely slow, it can also make it much harder to find a good -solution, as we will see. This problem is often referred to as the -curse of dimensionality. Fortunately, in real-world problems, it is -often possible to reduce the number of features considerably, turning -an intractable problem into a tractable one. - -Here we will discuss some of the most popular dimensionality reduction -techniques: the principal component analysis PCA, Kernel PCA, and -Locally Linear Embedding (LLE). Furthermore, we will start by looking -at some simple preprocessing of the data which allow us to rescale the -data. -% --- end paragraph admon --- - - - - -% !split -\subsection*{Preprocessing our data} - -% --- begin paragraph admon --- -\paragraph{} - -Before we proceed however, we will discuss how to preprocess our -data. Till now and in connection with our previous examples we have -not met so many cases where we are too sensitive to the scaling of our -data. Normally the data may need a rescaling and/or may be sensitive -to extreme values. Scaling the data renders our inputs much more -suitable for the algorithms we want to employ. - -\textbf{Scikit-Learn} has several functions which allow us to rescale the -data, normally resulting in much better results in terms of various -accuracy scores. The \textbf{StandardScaler} function in \textbf{Scikit-Learn} -ensures that for each feature/predictor we study the mean value is -zero and the variance is one (every column in the design/feature -matrix). This scaling has the drawback that it does not ensure that -we have a particular maximum or minimum in our data set. Another -function included in \textbf{Scikit-Learn} is the \textbf{MinMaxScaler} which -ensures that all features are exactly between $0$ and $1$. The - -% !split -\subsection*{More preprocessing} - - -The \textbf{Normalizer} scales each data -point such that the feature vector has a euclidean length of one. In other words, it -projects a data point on the circle (or sphere in the case of higher dimensions) with a -radius of 1. This means every data point is scaled by a different number (by the -inverse of it’s length). -This normalization is often used when only the direction (or angle) of the data matters, -not the length of the feature vector. - -The \textbf{RobustScaler} works similarly to the StandardScaler in that it -ensures statistical properties for each feature that guarantee that -they are on the same scale. However, the RobustScaler uses the median -and quartiles, instead of mean and variance. This makes the -RobustScaler ignore data points that are very different from the rest -(like measurement errors). These odd data points are also called -outliers, and might often lead to trouble for other scaling -techniques. -% --- end paragraph admon --- - - - -% !split -\subsection*{Simple preprocessing examples, Franke function and regression} - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -# Common imports -import os -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -import sklearn.linear_model as skl -from sklearn.metrics import mean_squared_error -from sklearn.model_selection import train_test_split -from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer -from sklearn.svm import SVR - -# 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') - - -def FrankeFunction(x,y): - term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2)) - term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1)) - term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2)) - term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2) - return term1 + term2 + term3 + term4 - - -def create_X(x, y, n ): - if len(x.shape) > 1: - x = np.ravel(x) - y = np.ravel(y) - - N = len(x) - l = int((n+1)*(n+2)/2) # Number of elements in beta - X = np.ones((N,l)) - - for i in range(1,n+1): - q = int((i)*(i+1)/2) - for k in range(i+1): - X[:,q+k] = (x**(i-k))*(y**k) - - return X - - -# Making meshgrid of datapoints and compute Franke's function -n = 5 -N = 1000 -x = np.sort(np.random.uniform(0, 1, N)) -y = np.sort(np.random.uniform(0, 1, N)) -z = FrankeFunction(x, y) -X = create_X(x, y, n=n) -# split in training and test data -X_train, X_test, y_train, y_test = train_test_split(X,z,test_size=0.2) - - -svm = SVR(gamma='auto',C=10.0) -svm.fit(X_train, y_train) - -# The mean squared error and R2 score -print("MSE before scaling: {:.2f}".format(mean_squared_error(svm.predict(X_test), y_test))) -print("R2 score before scaling {:.2f}".format(svm.score(X_test,y_test))) - -scaler = StandardScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) - -print("Feature min values before scaling:\n {}".format(X_train.min(axis=0))) -print("Feature max values before scaling:\n {}".format(X_train.max(axis=0))) - -print("Feature min values after scaling:\n {}".format(X_train_scaled.min(axis=0))) -print("Feature max values after scaling:\n {}".format(X_train_scaled.max(axis=0))) - -svm = SVR(gamma='auto',C=10.0) -svm.fit(X_train_scaled, y_train) - -print("MSE after scaling: {:.2f}".format(mean_squared_error(svm.predict(X_test_scaled), y_test))) -print("R2 score for scaled data: {:.2f}".format(svm.score(X_test_scaled,y_test))) - -\end{minted} - - - -% !split -\subsection*{Simple preprocessing examples, breast cancer data and classification, Support Vector Machines} - -We show here how we can use a simple regression case on the breast -cancer data using support vector machines (SVM) as algorithm for -classification. - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import matplotlib.pyplot as plt -import numpy as np -from sklearn.model_selection import train_test_split -from sklearn.datasets import load_breast_cancer -from sklearn.svm import SVC -cancer = load_breast_cancer() - -X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0) -print(X_train.shape) -print(X_test.shape) - -svm = SVC(C=100) -svm.fit(X_train, y_train) -print("Test set accuracy: {:.2f}".format(svm.score(X_test,y_test))) - -from sklearn.preprocessing import MinMaxScaler, StandardScaler -scaler = MinMaxScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) - -print("Feature min values before scaling:\n {}".format(X_train.min(axis=0))) -print("Feature max values before scaling:\n {}".format(X_train.max(axis=0))) - -print("Feature min values before scaling:\n {}".format(X_train_scaled.min(axis=0))) -print("Feature max values before scaling:\n {}".format(X_train_scaled.max(axis=0))) - - -svm.fit(X_train_scaled, y_train) -print("Test set accuracy scaled data with Min-Max scaling: {:.2f}".format(svm.score(X_test_scaled,y_test))) - -scaler = StandardScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) - -svm.fit(X_train_scaled, y_train) -print("Test set accuracy scaled data with Standar Scaler: {:.2f}".format(svm.score(X_test_scaled,y_test))) - -\end{minted} - -% !split -\subsection*{More on Cancer Data, now with Logistic Regression} - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import matplotlib.pyplot as plt -import numpy as np -from sklearn.model_selection import train_test_split -from sklearn.datasets import load_breast_cancer -from sklearn.linear_model import LogisticRegression -cancer = load_breast_cancer() - -# Set up training data -X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0) -logreg = LogisticRegression() -logreg.fit(X_train, y_train) -print("Test set accuracy: {:.2f}".format(logreg.score(X_test,y_test))) - -# Scale data -from sklearn.preprocessing import StandardScaler -scaler = StandardScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) -logreg.fit(X_train_scaled, y_train) -print("Test set accuracy scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) - -\end{minted} - - - - -% !split -\subsection*{Why should we think of reducing the dimensionality} - -In addition to the plot of the features, we study now also the covariance (or rather the correlation matrix). -We use also \textbf{Pandas} to compute the correlation matrix. -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import matplotlib.pyplot as plt -import numpy as np -from sklearn.model_selection import train_test_split -from sklearn.datasets import load_breast_cancer -from sklearn.linear_model import LogisticRegression -cancer = load_breast_cancer() -import pandas as pd -# Making a data frame -cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names) - -fig, axes = plt.subplots(15,2,figsize=(10,20)) -malignant = cancer.data[cancer.target == 0] -benign = cancer.data[cancer.target == 1] -ax = axes.ravel() - -for i in range(30): - _, bins = np.histogram(cancer.data[:,i], bins =50) - ax[i].hist(malignant[:,i], bins = bins, alpha = 0.5) - ax[i].hist(benign[:,i], bins = bins, alpha = 0.5) - ax[i].set_title(cancer.feature_names[i]) - ax[i].set_yticks(()) -ax[0].set_xlabel("Feature magnitude") -ax[0].set_ylabel("Frequency") -ax[0].legend(["Malignant", "Benign"], loc ="best") -fig.tight_layout() -plt.show() - -import seaborn as sns -correlation_matrix = cancerpd.corr().round(1) -# use the heatmap function from seaborn to plot the correlation matrix -# annot = True to print the values inside the square -sns.heatmap(data=correlation_matrix, annot=True) -plt.show() - -#print eigvalues of correlation matrix -EigValues, EigVectors = np.linalg.eig(correlation_matrix) -print(EigValues) -\end{minted} - -In the above example we note two things. In the first plot we display -the overlap of benign and malignant tumors as functions of the various -features in the Wisconsing breast cancer data set. We see that for -some of the features we can distinguish clearly the benign and -malignant cases while for other features we cannot. This can point to -us which features may be of greater interest when we wish to classify -a benign or not benign tumour. - -In the second figure we have computed the so-called correlation -matrix, which in our case with thirty features becomes a $30\times 30$ -matrix. - -We constructed this matrix using \textbf{pandas} via the statements -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names) -\end{minted} -and then -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -correlation_matrix = cancerpd.corr().round(1) -\end{minted} - -Diagonalizing this matrix we can in turn say something about which -features are of relevance and which are not. But before we proceed we -need to define covariance and correlation matrices. This leads us to -the classical Principal Component Analysis (PCA) theorem with -applications. - - - -% !split -\subsection*{Basic ideas of the Principal Component Analysis (PCA)} - -We have a data set defined by a design/feature matrix $\bm{X}$ (see below for its definition) -\begin{itemize} -\item Each data point is determined by $p$ extrinsic (measurement) variables - -\item We may want to ask the following question: Are there fewer intrinsic variables (say $d << p$) that still approximately describe the data? - -\item If so, these intrinsic variables may tell us something important and finding these intrinsic variables is what dimension reduction methods do. -\end{itemize} - -\noindent -% !split -\subsection*{Introducing the Covariance and Correlation functions} - -Before we discuss the PCA theorem, we need to remind ourselves about -the definition of the covariance and the correlation function. - -Suppose we have defined two vectors -$\hat{x}$ and $\hat{y}$ with $n$ elements each. The covariance matrix $\bm{C}$ is defined as -\[ -\bm{C}[\bm{x},\bm{y}] = \begin{bmatrix} \mathrm{cov}[\bm{x},\bm{x}] & \mathrm{cov}[\bm{x},\bm{y}] \\ - \mathrm{cov}[\bm{y},\bm{x}] & \mathrm{cov}[\bm{y},\bm{y}] \\ - \end{bmatrix}, -\] -where for example -\[ -\mathrm{cov}[\bm{x},\bm{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). -\] -With this definition and recalling that the variance is defined as -\[ -\mathrm{var}[\bm{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2, -\] -we can rewrite the covariance matrix as -\[ -\bm{C}[\bm{x},\bm{y}] = \begin{bmatrix} \mathrm{var}[\bm{x}] & \mathrm{cov}[\bm{x},\bm{y}] \\ - \mathrm{cov}[\bm{x},\bm{y}] & \mathrm{var}[\bm{y}] \\ - \end{bmatrix}. -\] - -The covariance takes values between zero and infinity and may thus -lead to problems with loss of numerical precision for particularly -large values. It is common to scale the covariance matrix by -introducing instead the correlation matrix defined via the so-called -correlation function - -\[ -\mathrm{corr}[\bm{x},\bm{y}]=\frac{\mathrm{cov}[\bm{x},\bm{y}]}{\sqrt{\mathrm{var}[\bm{x}] \mathrm{var}[\bm{y}]}}. -\] - -The correlation function is then given by values $\mathrm{corr}[\bm{x},\bm{y}] -\in [-1,1]$. This avoids eventual problems with too large values. We -can then define the correlation matrix for the two vectors $\bm{x}$ -and $\bm{y}$ as - -\[ -\bm{K}[\bm{x},\bm{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\bm{x},\bm{y}] \\ - \mathrm{corr}[\bm{y},\bm{x}] & 1 \\ - \end{bmatrix}, -\] - -In the above example this is the function we constructed using \textbf{pandas}. - -% !split -\subsection*{Correlation Function and Design/Feature Matrix} - -In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression we defined the design/feature matrix $\bm{X}$ as -\[ -\bm{X}=\begin{bmatrix} -x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ -x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ -x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ -\dots & \dots & \dots & \dots \dots & \dots \\ -x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ -x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ -\end{bmatrix}, -\] -with $\bm{X}\in {\mathbb{R}}^{n\times p}$, with the predictors/features $p$ refering to the column numbers and the -entries $n$ being the row elements. -We can rewrite the design/feature matrix in terms of its column vectors as -\[ -\bm{X}=\begin{bmatrix} \bm{x}_0 & \bm{x}_0 & \bm{x}_0 & \dots & \dots & \bm{x}_{p-1}\end{bmatrix}, -\] -with a given vector -\[ -\bm{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}. -\] - -With these definitions, we can now rewrite our $2\times 2$ correaltion/covariance matrix in terms of a moe general design/feature matrix $\bm{X}\in {\mathbb{R}}^{n\times p}$. This leads to a $p\times p$ covariance matrix for the vectors $\bm{x}_i$ with $i =0,1,\dots,p-1$ -\[ -\bm{C}[\bm{x}] = \begin{bmatrix} -\mathrm{var}[\bm{x}_0] & \mathrm{cov}[\bm{x}_0,\bm{x}_1] & \mathrm{cov}[\bm{x}_0,\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_0,\bm{x}_{p-1}]\\ -\mathrm{cov}[\bm{x}_1,\bm{x}_0] & \mathrm{var}[\bm{x}_1] & \mathrm{cov}[\bm{x}_1,\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_1,\bm{x}_{p-1}]\\ -\mathrm{cov}[\bm{x}_2,\bm{x}_0] & \mathrm{cov}[\bm{x}_2,\bm{x}_1] & \mathrm{var}[\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_2,\bm{x}_{p-1}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\mathrm{cov}[\bm{x}_{p-1},\bm{x}_0] & \mathrm{cov}[\bm{x}_{p-1},\bm{x}_1] & \mathrm{cov}[\bm{x}_{p-1},\bm{x}_{2}] & \dots & \dots & \mathrm{var}[\bm{x}_{p-1}]\\ -\end{bmatrix}, -\] -and the correlation matrix -\[ -\bm{K}[\bm{x}] = \begin{bmatrix} -1 & \mathrm{corr}[\bm{x}_0,\bm{x}_1] & \mathrm{corr}[\bm{x}_0,\bm{x}_2] & \dots & \dots & \mathrm{corr}[\bm{x}_0,\bm{x}_{p-1}]\\ -\mathrm{corr}[\bm{x}_1,\bm{x}_0] & 1 & \mathrm{corr}[\bm{x}_1,\bm{x}_2] & \dots & \dots & \mathrm{corr}[\bm{x}_1,\bm{x}_{p-1}]\\ -\mathrm{corr}[\bm{x}_2,\bm{x}_0] & \mathrm{corr}[\bm{x}_2,\bm{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\bm{x}_2,\bm{x}_{p-1}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\mathrm{corr}[\bm{x}_{p-1},\bm{x}_0] & \mathrm{corr}[\bm{x}_{p-1},\bm{x}_1] & \mathrm{corr}[\bm{x}_{p-1},\bm{x}_{2}] & \dots & \dots & 1\\ -\end{bmatrix}, -\] - - -% !split -\subsection*{Covariance Matrix Examples} - - -The Numpy function \textbf{np.cov} calculates the covariance elements using -the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have -the exact mean values. The following simple function uses the -\textbf{np.vstack} function which takes each vector of dimension $1\times n$ -and produces a $2\times n$ matrix $\bm{W}$ - - -\[ -\bm{W} = \begin{bmatrix} x_0 & y_0 \\ - x_1 & y_1 \\ - x_2 & y_2\\ - \dots & \dots \\ - x_{n-2} & y_{n-2}\\ - x_{n-1} & y_{n-1} & - \end{bmatrix}, -\] - -which in turn is converted into into the $2\times 2$ covariance matrix -$\bm{C}$ via the Numpy function \textbf{np.cov()}. We note that we can also calculate -the mean value of each set of samples $\bm{x}$ etc using the Numpy -function \textbf{np.mean(x)}. We can also extract the eigenvalues of the -covariance matrix through the \textbf{np.linalg.eig()} function. - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -# Importing various packages -import numpy as np -n = 100 -x = np.random.normal(size=n) -print(np.mean(x)) -y = 4+3*x+np.random.normal(size=n) -print(np.mean(y)) -W = np.vstack((x, y)) -C = np.cov(W) -print(C) -\end{minted} - -% !split -\subsection*{Correlation Matrix} - -The previous example can be converted into the correlation matrix by -simply scaling the matrix elements with the variances. We should also -subtract the mean values for each column. This leads to the following -code which sets up the correlations matrix for the previous example in -a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the $2\times 2$ correlation matrix (since we have only two vectors). - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import numpy as np -n = 100 -# define two vectors -x = np.random.random(size=n) -y = 4+3*x+np.random.normal(size=n) -#scaling the x and y vectors -x = x - np.mean(x) -y = y - np.mean(y) -variance_x = np.sum(x@x)/n -variance_y = np.sum(y@y)/n -print(variance_x) -print(variance_y) -cov_xy = np.sum(x@y)/n -cov_xx = np.sum(x@x)/n -cov_yy = np.sum(y@y)/n -C = np.zeros((2,2)) -C[0,0]= cov_xx/variance_x -C[1,1]= cov_yy/variance_y -C[0,1]= cov_xy/np.sqrt(variance_y*variance_x) -C[1,0]= C[0,1] -print(C) -\end{minted} - -We see that the matrix elements along the diagonal are one as they -should be and that the matrix is symmetric. Furthermore, diagonalizing -this matrix we easily see that it is a positive definite matrix. - -The above procedure with \textbf{numpy} can be made more compact if we use \textbf{pandas}. - -% !split -\subsection*{Correlation Matrix with Pandas} - -We whow here how we can set up the correlation matrix using \textbf{pandas}, as done in this simple code -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import numpy as np -import pandas as pd -n = 10 -x = np.random.normal(size=n) -x = x - np.mean(x) -y = 4+3*x+np.random.normal(size=n) -y = y - np.mean(y) -X = (np.vstack((x, y))).T -print(X) -Xpd = pd.DataFrame(X) -print(Xpd) -correlation_matrix = Xpd.corr() -print(correlation_matrix) -\end{minted} - - -We expand this model to the Franke function discussed above. - -% !split -\subsection*{Correlation Matrix with Pandas and the Franke function} - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -# Common imports -import numpy as np -import pandas as pd - - -def FrankeFunction(x,y): - term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2)) - term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1)) - term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2)) - term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2) - return term1 + term2 + term3 + term4 - - -def create_X(x, y, n ): - if len(x.shape) > 1: - x = np.ravel(x) - y = np.ravel(y) - - N = len(x) - l = int((n+1)*(n+2)/2) # Number of elements in beta - X = np.ones((N,l)) - - for i in range(1,n+1): - q = int((i)*(i+1)/2) - for k in range(i+1): - X[:,q+k] = (x**(i-k))*(y**k) - - return X - - -# Making meshgrid of datapoints and compute Franke's function -n = 4 -N = 100 -x = np.sort(np.random.uniform(0, 1, N)) -y = np.sort(np.random.uniform(0, 1, N)) -z = FrankeFunction(x, y) -X = create_X(x, y, n=n) - -Xpd = pd.DataFrame(X) -# subtract the mean values and set up the covariance matrix -Xpd = Xpd - Xpd.mean() -covariance_matrix = Xpd.cov() -print(covariance_matrix) -\end{minted} - -We note here that the covariance is zero for the first rows and -columns since all matrix elements in the design matrix were set to one -(we are fitting the function in terms of a polynomial of degree $n$). - -This means that the variance for these elements will be zero and will -cause problems when we set up the correlation matrix. We can simply -drop these elements as follows and then construct the correlation -matrix. - - -% !split -\subsection*{Rewriting the Covariance and/or Correlation Matrix} - -We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\bm{X}$ as -\[ -\bm{C}[\bm{x}] = \frac{1}{n}\bm{X}\bm{X}^T= \mathbb{E}[\bm{X}\bm{X}^T]. -\] - -To see this let us simply look at a design matrix $\bm{X}\in {\mathbb{R}}^{2\times 2}$ -\[ -\bm{X}=\begin{bmatrix} -x_{00} & x_{01}\\ -x_{10} & x_{11}\\ -\end{bmatrix}=\begin{bmatrix} -\bm{x}_{0} & \bm{x}_{1}\\ -\end{bmatrix}. -\] - -If we then compute the expectation value -\[ -\mathbb{E}[\bm{X}\bm{X}^T] = \frac{1}{n}\bm{X}\bm{X}^T=\begin{bmatrix} -x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\ -x_{10}x_{00}+x_{01}x_{11} & x_{10}^2+x_{11}^2\\ -\end{bmatrix}, -\] -which is just -\[ -\bm{C}[\bm{x}_0,\bm{x}_1] = \bm{C}[\bm{x}]=\begin{bmatrix} \mathrm{var}[\bm{x}_0] & \mathrm{cov}[\bm{x}_0,\bm{x}_1] \\ - \mathrm{cov}[\bm{x}_1,\bm{x}_0] & \mathrm{var}[\bm{x}_1] \\ - \end{bmatrix}, -\] -where we wrote $$\bm{C}[\bm{x}_0,\bm{x}_1] = \bm{C}[\bm{x}]$$ to indicate that this the covariance of the vectors $\bm{x}$ of the design/feature matrix $\bm{X}$. - -It is easy to generalize this to a matrix $\bm{X}\in {\mathbb{R}}^{n\times p}$. - - -% !split -\subsection*{Towards the PCA theorem} - -We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as -\[ -\bm{C}[\bm{x}] = \frac{1}{n}\bm{X}\bm{X}^T= \mathbb{E}[\bm{X}\bm{X}^T]. -\] -Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices $\bm{S}$. -These matrices are defined as $\bm{S}\in {\mathbb{R}}^{p\times p}$ and obey the orthogonality requirements $\bm{S}\bm{S}^T=\bm{S}^T\bm{S}=\bm{I}$. The matrix can be written out in terms of the column vectors $\bm{s}_i$ as $\bm{S}=[\bm{s}_0,\bm{s}_1,\dots,\bm{s}_{p-1}]$ and $\bm{s}_i \in {\mathbb{R}}^{p}$. - -Assume also that there is a transformation $\bm{S}\bm{C}[\bm{x}]\bm{S}^T=\bm{C}[\bm{y}]$ such that the new matrix $\bm{C}[\bm{y}]$ is diagonal with elements $[\lambda_0,\lambda_1,\lambda_2,\dots,\lambda_{p-1}]$. - -That is we have -\[ -\bm{C}[\bm{y}] = \mathbb{E}[\bm{S}\bm{X}\bm{X}^T\bm{S}^T]=\bm{S}\bm{C}[\bm{x}]\bm{S}^T, -\] -since the matrix $\bm{S}$ is not a data dependent matrix. Multiplying with $\bm{S}^T$ from the left we have -\[ -\bm{S}^T\bm{C}[\bm{y}] = \bm{C}[\bm{x}]\bm{S}^T, -\] -and since $\bm{C}[\bm{y}]$ is diagonal we have for a given eigenvalue $i$ of the covariance matrix that - -\[ -\bm{S}^T_i\lambda_i = \bm{C}[\bm{x}]\bm{S}^T_i. -\] - -In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is -$\lambda_0 > \lambda_1 > \dots > \lambda_{p-1}$. - -% !split -\subsection*{Classical PCA Theorem} - - - -% !split -\subsection*{Prof of the PCA Theorem} - - - - - - -% !split -\subsection*{Getting started with PCA} - - -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -# Now add PCA -from sklearn.decomposition import PCA -pca = PCA(n_components = 2) -pca.fit(X_train_scaled) - -X_pca = pca.transform(X_train_scaled) -\end{minted} - - - -% !split -\subsection*{Principal Component Analysis} - -% --- begin paragraph admon --- -\paragraph{} -Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm. -First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it. - -The following Python code uses NumPy’s \textbf{svd()} function to obtain all the principal components of the -training set, then extracts the first two principal components -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -X_centered = X - X.mean(axis=0) -U, s, V = np.linalg.svd(X_centered) -c1 = V.T[:, 0] -c2 = V.T[:, 1] -\end{minted} - -PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering -the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t -forget to center the data first. - -Once you have identified all the principal components, you can reduce the dimensionality of the dataset -down to $d$ dimensions by projecting it onto the hyperplane defined by the first $d$ principal components. -Selecting this hyperplane ensures that the projection will preserve as much variance as possible. -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -W2 = V.T[:, :2] -X2D = X_centered.dot(W2) -\end{minted} - -% !split -\subsection*{PCA and scikit-learn} - -Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The -following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note -that it automatically takes care of centering the data): -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -from sklearn.decomposition import PCA -pca = PCA(n_components = 2) -X2D = pca.fit_transform(X) -\end{minted} -After fitting the PCA transformer to the dataset, you can access the principal components using the -components variable (note that it contains the PCs as horizontal vectors, so, for example, the first -principal component is equal to -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -pca.components_.T[:, 0]). -\end{minted} -Another very useful piece of information is the explained variance ratio of each principal component, -available via the $explained\_variance\_ratio$ variable. It indicates the proportion of the dataset’s -variance that lies along the axis of each principal component. -More material to come here. - -% !split -\subsection*{More on the PCA} - -Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to -choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95\%). -Unless, of course, you are reducing dimensionality for data visualization — in that case you will -generally want to reduce the dimensionality down to 2 or 3. -The following code computes PCA without reducing dimensionality, then computes the minimum number -of dimensions required to preserve 95\% of the training set’s variance: -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -pca = PCA() -pca.fit(X) -cumsum = np.cumsum(pca.explained_variance_ratio_) -d = np.argmax(cumsum >= 0.95) + 1 -\end{minted} -You could then set $n\_components=d$ and run PCA again. However, there is a much better option: instead -of specifying the number of principal components you want to preserve, you can set $n\_components$ to be -a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve: -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -pca = PCA(n_components=0.95) -X_reduced = pca.fit_transform(X) -\end{minted} - -% !split -\subsection*{Incremental PCA} - -One problem with the preceding implementation of PCA is that it requires the whole training set to fit in -memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have -been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch -at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new -instances arrive). - -% !split -\subsection*{Randomized PCA} - -Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic -algorithm that quickly finds an approximation of the first d principal components. Its computational -complexity is $O(m \times d^2)+O(d^3)$, instead of $O(m \times n^2) + O(n^3)$, so it is dramatically faster than the -previous algorithms when $d$ is much smaller than $n$. -% --- end paragraph admon --- - - - - -% !split -\subsection*{Kernel PCA} - -% --- begin paragraph admon --- -\paragraph{} - -The kernel trick is a mathematical technique that implicitly maps instances into a -very high-dimensional space (called the feature space), enabling nonlinear classification and regression -with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature -space corresponds to a complex nonlinear decision boundary in the original space. -It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear -projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at -preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a -twisted manifold. -For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -from sklearn.decomposition import KernelPCA -rbf_pca = KernelPCA(n_components = 2, kernel="rbf", gamma=0.04) -X_reduced = rbf_pca.fit_transform(X) -\end{minted} -% --- end paragraph admon --- - - - - -% !split -\subsection*{LLE} - -Locally Linear Embedding (LLE) is another very powerful nonlinear dimensionality reduction -(NLDR) technique. It is a Manifold Learning technique that does not rely on projections like the previous -algorithms. In a nutshell, LLE works by first measuring how each training instance linearly relates to its -closest neighbors (c.n.), and then looking for a low-dimensional representation of the training set where -these local relationships are best preserved (more details shortly). - - - -% !split -\subsection*{Other techniques} - - -There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn. - -Here are some of the most popular: -\begin{itemize} -\item \textbf{Multidimensional Scaling (MDS)} reduces dimensionality while trying to preserve the distances between the instances. - -\item \textbf{Isomap} creates a graph by connecting each instance to its nearest neighbors, then reduces dimensionality while trying to preserve the geodesic distances between the instances. - -\item \textbf{t-Distributed Stochastic Neighbor Embedding} (t-SNE) reduces dimensionality while trying to keep similar instances close and dissimilar instances apart. It is mostly used for visualization, in particular to visualize clusters of instances in high-dimensional space (e.g., to visualize the MNIST images in 2D). - -\item Linear Discriminant Analysis (LDA) is actually a classification algorithm, but during training it learns the most discriminative axes between the classes, and these axes can then be used to define a hyperplane onto which to project the data. The benefit is that the projection will keep classes as far apart as possible, so LDA is a good technique to reduce dimensionality before running another classification algorithm such as a Support Vector Machine (SVM) classifier discussed in the SVM lectures. -\end{itemize} - -\noindent -Here are other examples where we use the \textbf{DataFrame} functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix -of dimensionality $10\times 5$ and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations. -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -import numpy as np -import pandas as pd -from IPython.display import display -np.random.seed(100) -# setting up a 10 x 5 matrix -rows = 10 -cols = 5 -a = np.random.randn(rows,cols) -df = pd.DataFrame(a) -display(df) -print(df.mean()) -print(df.std()) -display(df**2) -\end{minted} - -Thereafter we can select specific columns only and plot final results -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth'] -df.index = np.arange(10) - -display(df) -print(df['Second'].mean() ) -print(df.info()) -print(df.describe()) - -from pylab import plt, mpl -plt.style.use('seaborn') -mpl.rcParams['font.family'] = 'serif' - -df.cumsum().plot(lw=2.0, figsize=(10,6)) -plt.show() - - -df.plot.bar(figsize=(10,6), rot=15) -plt.show() -\end{minted} -We can produce a $4\times 4$ matrix -\begin{minted}[fontsize=\fontsize{9pt}{9pt},linenos=false,mathescape,baselinestretch=1.0,fontfamily=tt,xleftmargin=7mm]{python} -b = np.arange(16).reshape((4,4)) -print(b) -df1 = pd.DataFrame(b) -print(df1) -\end{minted} -and many other operations. - - -% ------------------- end of main content --------------- - -\end{document} - diff --git a/doc/src/DimRed/README.txt b/doc/src/DimRed/README.txt deleted file mode 100644 index e435e6055..000000000 --- a/doc/src/DimRed/README.txt +++ /dev/null @@ -1,2 +0,0 @@ -This IPython notebook DimRed.ipynb does not require any additional -programs. diff --git a/doc/src/DimRed/_minted-DimRed/default.pygstyle b/doc/src/DimRed/_minted-DimRed/default.pygstyle deleted file mode 100644 index e69de29bb..000000000 diff --git a/doc/src/DimRed/ipynb-DimRed-src.tar.gz b/doc/src/DimRed/ipynb-DimRed-src.tar.gz deleted file mode 100644 index 0eef6c592..000000000 Binary files a/doc/src/DimRed/ipynb-DimRed-src.tar.gz and /dev/null differ diff --git a/doc/src/DimRed/reveal.js/.gitignore b/doc/src/DimRed/reveal.js/.gitignore deleted file mode 100644 index a5df3133d..000000000 --- a/doc/src/DimRed/reveal.js/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -.DS_Store -.svn -log/*.log -tmp/** -node_modules/ -.sass-cache -css/reveal.min.css -js/reveal.min.js diff --git a/doc/src/DimRed/reveal.js/.travis.yml b/doc/src/DimRed/reveal.js/.travis.yml deleted file mode 100644 index 165d9ae9f..000000000 --- a/doc/src/DimRed/reveal.js/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: node_js -node_js: - - 0.10 -before_script: - - npm install -g grunt-cli \ No newline at end of file diff --git a/doc/src/DimRed/reveal.js/CONTRIBUTING.md b/doc/src/DimRed/reveal.js/CONTRIBUTING.md deleted file mode 100644 index c2091e88f..000000000 --- a/doc/src/DimRed/reveal.js/CONTRIBUTING.md +++ /dev/null @@ -1,23 +0,0 @@ -## Contributing - -Please keep the [issue tracker](http://github.com/hakimel/reveal.js/issues) limited to **bug reports**, **feature requests** and **pull requests**. - - -### Personal Support -If you have personal support or setup questions the best place to ask those are [StackOverflow](http://stackoverflow.com/questions/tagged/reveal.js). - - -### Bug Reports -When reporting a bug make sure to include information about which browser and operating system you are on as well as the necessary steps to reproduce the issue. If possible please include a link to a sample presentation where the bug can be tested. - - -### Pull Requests -- Should follow the coding style of the file you work in, most importantly: - - Tabs to indent - - Single-quoted strings -- Should be made towards the **dev branch** -- Should be submitted from a feature/topic branch (not your master) - - -### Plugins -Please do not submit plugins as pull requests. They should be maintained in their own separate repository. More information here: https://github.com/hakimel/reveal.js/wiki/Plugin-Guidelines diff --git a/doc/src/DimRed/reveal.js/Gruntfile.js b/doc/src/DimRed/reveal.js/Gruntfile.js deleted file mode 100644 index b257e8f32..000000000 --- a/doc/src/DimRed/reveal.js/Gruntfile.js +++ /dev/null @@ -1,140 +0,0 @@ -/* global module:false */ -module.exports = function(grunt) { - var port = grunt.option('port') || 8000; - // Project configuration - grunt.initConfig({ - pkg: grunt.file.readJSON('package.json'), - meta: { - banner: - '/*!\n' + - ' * reveal.js <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' + - ' * http://lab.hakim.se/reveal-js\n' + - ' * MIT licensed\n' + - ' *\n' + - ' * Copyright (C) 2014 Hakim El Hattab, http://hakim.se\n' + - ' */' - }, - - qunit: { - files: [ 'test/*.html' ] - }, - - uglify: { - options: { - banner: '<%= meta.banner %>\n' - }, - build: { - src: 'js/reveal.js', - dest: 'js/reveal.min.js' - } - }, - - cssmin: { - compress: { - files: { - 'css/reveal.min.css': [ 'css/reveal.css' ] - } - } - }, - - sass: { - main: { - files: { - 'css/theme/darkgray.css': 'css/theme/source/darkgray.scss', - 'css/theme/beigesmall.css': 'css/theme/source/beigesmall.scss', - 'css/theme/cbc.css': 'css/theme/source/cbc.scss', - 'css/theme/default.css': 'css/theme/source/default.scss', - 'css/theme/beige.css': 'css/theme/source/beige.scss', - 'css/theme/night.css': 'css/theme/source/night.scss', - 'css/theme/serif.css': 'css/theme/source/serif.scss', - 'css/theme/simple.css': 'css/theme/source/simple.scss', - 'css/theme/sky.css': 'css/theme/source/sky.scss', - 'css/theme/moon.css': 'css/theme/source/moon.scss', - 'css/theme/solarized.css': 'css/theme/source/solarized.scss', - 'css/theme/blood.css': 'css/theme/source/blood.scss' - } - } - }, - - jshint: { - options: { - curly: false, - eqeqeq: true, - immed: true, - latedef: true, - newcap: true, - noarg: true, - sub: true, - undef: true, - eqnull: true, - browser: true, - expr: true, - globals: { - head: false, - module: false, - console: false, - unescape: false - } - }, - files: [ 'Gruntfile.js', 'js/reveal.js' ] - }, - - connect: { - server: { - options: { - port: port, - base: '.' - } - } - }, - - zip: { - 'reveal-js-presentation.zip': [ - 'index.html', - 'css/**', - 'js/**', - 'lib/**', - 'images/**', - 'plugin/**' - ] - }, - - watch: { - main: { - files: [ 'Gruntfile.js', 'js/reveal.js', 'css/reveal.css' ], - tasks: 'default' - }, - theme: { - files: [ 'css/theme/source/*.scss', 'css/theme/template/*.scss' ], - tasks: 'themes' - } - } - - }); - - // Dependencies - grunt.loadNpmTasks( 'grunt-contrib-qunit' ); - grunt.loadNpmTasks( 'grunt-contrib-jshint' ); - grunt.loadNpmTasks( 'grunt-contrib-cssmin' ); - grunt.loadNpmTasks( 'grunt-contrib-uglify' ); - grunt.loadNpmTasks( 'grunt-contrib-watch' ); - grunt.loadNpmTasks( 'grunt-contrib-sass' ); - grunt.loadNpmTasks( 'grunt-contrib-connect' ); - grunt.loadNpmTasks( 'grunt-zip' ); - - // Default task - grunt.registerTask( 'default', [ 'jshint', 'cssmin', 'uglify', 'qunit' ] ); - - // Theme task - grunt.registerTask( 'themes', [ 'sass' ] ); - - // Package presentation to archive - grunt.registerTask( 'package', [ 'default', 'zip' ] ); - - // Serve presentation locally - grunt.registerTask( 'serve', [ 'connect', 'watch' ] ); - - // Run tests - grunt.registerTask( 'test', [ 'jshint', 'qunit' ] ); - -}; diff --git a/doc/src/DimRed/reveal.js/LICENSE b/doc/src/DimRed/reveal.js/LICENSE deleted file mode 100644 index 09623076f..000000000 --- a/doc/src/DimRed/reveal.js/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (C) 2015 Hakim El Hattab, http://hakim.se - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/doc/src/DimRed/reveal.js/README.md b/doc/src/DimRed/reveal.js/README.md deleted file mode 100644 index 573b19597..000000000 --- a/doc/src/DimRed/reveal.js/README.md +++ /dev/null @@ -1,1052 +0,0 @@ -# reveal.js [![Build Status](https://travis-ci.org/hakimel/reveal.js.svg?branch=master)](https://travis-ci.org/hakimel/reveal.js) - -A framework for easily creating beautiful presentations using HTML. [Check out the live demo](http://lab.hakim.se/reveal-js/). - -reveal.js comes with a broad range of features including [nested slides](https://github.com/hakimel/reveal.js#markup), [Markdown contents](https://github.com/hakimel/reveal.js#markdown), [PDF export](https://github.com/hakimel/reveal.js#pdf-export), [speaker notes](https://github.com/hakimel/reveal.js#speaker-notes) and a [JavaScript API](https://github.com/hakimel/reveal.js#api). It's best viewed in a modern browser but [fallbacks](https://github.com/hakimel/reveal.js/wiki/Browser-Support) are available to make sure your presentation can still be viewed elsewhere. - - -#### More reading: -- [Installation](#installation): Step-by-step instructions for getting reveal.js running on your computer. -- [Changelog](https://github.com/hakimel/reveal.js/releases): Up-to-date version history. -- [Examples](https://github.com/hakimel/reveal.js/wiki/Example-Presentations): Presentations created with reveal.js, add your own! -- [Browser Support](https://github.com/hakimel/reveal.js/wiki/Browser-Support): Explanation of browser support and fallbacks. -- [Plugins](https://github.com/hakimel/reveal.js/wiki/Plugins,-Tools-and-Hardware): A list of plugins that can be used to extend reveal.js. - -## Online Editor - -Presentations are written using HTML or Markdown but there's also an online editor for those of you who prefer a graphical interface. Give it a try at [http://slides.com](http://slides.com). - - -## Instructions - -### Markup - -Markup hierarchy needs to be ``
`` where the ``
`` represents one slide and can be repeated indefinitely. If you place multiple ``
``'s inside of another ``
`` they will be shown as vertical slides. The first of the vertical slides is the "root" of the others (at the top), and it will be included in the horizontal sequence. For example: - -```html -
-
-
Single Horizontal Slide
-
-
Vertical Slide 1
-
Vertical Slide 2
-
-
-
-``` - -### Markdown - -It's possible to write your slides using Markdown. To enable Markdown, add the ```data-markdown``` attribute to your ```
``` elements and wrap the contents in a ``` -
-``` - -#### External Markdown - -You can write your content as a separate file and have reveal.js load it at runtime. Note the separator arguments which determine how slides are delimited in the external file. The ```data-charset``` attribute is optional and specifies which charset to use when loading the external file. - -When used locally, this feature requires that reveal.js [runs from a local web server](#full-setup). - -```html -
-
-``` - -#### Element Attributes - -Special syntax (in html comment) is available for adding attributes to Markdown elements. This is useful for fragments, amongst other things. - -```html -
- -
-``` - -#### Slide Attributes - -Special syntax (in html comment) is available for adding attributes to the slide `
` elements generated by your Markdown. - -```html -
- -
-``` - - -### Configuration - -At the end of your page you need to initialize reveal by running the following code. Note that all config values are optional and will default as specified below. - -```javascript -Reveal.initialize({ - - // Display controls in the bottom right corner - controls: true, - - // Display a presentation progress bar - progress: true, - - // Display the page number of the current slide - slideNumber: false, - - // Push each slide change to the browser history - history: false, - - // Enable keyboard shortcuts for navigation - keyboard: true, - - // Enable the slide overview mode - overview: true, - - // Vertical centering of slides - center: true, - - // Enables touch navigation on devices with touch input - touch: true, - - // Loop the presentation - loop: false, - - // Change the presentation direction to be RTL - rtl: false, - - // Turns fragments on and off globally - fragments: true, - - // Flags if the presentation is running in an embedded mode, - // i.e. contained within a limited portion of the screen - embedded: false, - - // Flags if we should show a help overlay when the questionmark - // key is pressed - help: true, - - // Number of milliseconds between automatically proceeding to the - // next slide, disabled when set to 0, this value can be overwritten - // by using a data-autoslide attribute on your slides - autoSlide: 0, - - // Stop auto-sliding after user input - autoSlideStoppable: true, - - // Enable slide navigation via mouse wheel - mouseWheel: false, - - // Hides the address bar on mobile devices - hideAddressBar: true, - - // Opens links in an iframe preview overlay - previewLinks: false, - - // Transition style - transition: 'default', // none/fade/slide/convex/concave/zoom - - // Transition speed - transitionSpeed: 'default', // default/fast/slow - - // Transition style for full page slide backgrounds - backgroundTransition: 'default', // none/fade/slide/convex/concave/zoom - - // Number of slides away from the current that are visible - viewDistance: 3, - - // Parallax background image - parallaxBackgroundImage: '', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'" - - // Parallax background size - parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" - - // Amount to move parallax background (horizontal and vertical) on slide change - // Number, e.g. 100 - parallaxBackgroundHorizontal: '', - parallaxBackgroundVertical: '' - -}); -``` - - -The configuration can be updated after initialization using the ```configure``` method: - -```javascript -// Turn autoSlide off -Reveal.configure({ autoSlide: 0 }); - -// Start auto-sliding every 5s -Reveal.configure({ autoSlide: 5000 }); -``` - - -### Dependencies - -Reveal.js doesn't _rely_ on any third party scripts to work but a few optional libraries are included by default. These libraries are loaded as dependencies in the order they appear, for example: - -```javascript -Reveal.initialize({ - dependencies: [ - // Cross-browser shim that fully implements classList - https://github.com/eligrey/classList.js/ - { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, - - // Interpret Markdown in
elements - { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, - { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, - - // Syntax highlight for elements - { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }, - - // Zoom in and out with Alt+click - { src: 'plugin/zoom-js/zoom.js', async: true }, - - // Speaker notes - { src: 'plugin/notes/notes.js', async: true }, - - // Remote control your reveal.js presentation using a touch device - { src: 'plugin/remotes/remotes.js', async: true }, - - // MathJax - { src: 'plugin/math/math.js', async: true } - ] -}); -``` - -You can add your own extensions using the same syntax. The following properties are available for each dependency object: -- **src**: Path to the script to load -- **async**: [optional] Flags if the script should load after reveal.js has started, defaults to false -- **callback**: [optional] Function to execute when the script has loaded -- **condition**: [optional] Function which must return true for the script to be loaded - - -### Ready Event - -A 'ready' event is fired when reveal.js has loaded all non-async dependencies and is ready to start navigating. To check if reveal.js is already 'ready' you can call `Reveal.isReady()`. - -```javascript -Reveal.addEventListener( 'ready', function( event ) { - // event.currentSlide, event.indexh, event.indexv -} ); -``` - - -### Presentation Size - -All presentations have a normal size, that is the resolution at which they are authored. The framework will automatically scale presentations uniformly based on this size to ensure that everything fits on any given display or viewport. - -See below for a list of configuration options related to sizing, including default values: - -```javascript -Reveal.initialize({ - - ... - - // The "normal" size of the presentation, aspect ratio will be preserved - // when the presentation is scaled to fit different resolutions. Can be - // specified using percentage units. - width: 960, - height: 700, - - // Factor of the display size that should remain empty around the content - margin: 0.1, - - // Bounds for smallest/largest possible scale to apply to content - minScale: 0.2, - maxScale: 1.5 - -}); -``` - - -### Auto-sliding - -Presentations can be configured to progress through slides automatically, without any user input. To enable this you will need to tell the framework how many milliseconds it should wait between slides: - -```javascript -// Slide every five seconds -Reveal.configure({ - autoSlide: 5000 -}); -``` -When this is turned on a control element will appear that enables users to pause and resume auto-sliding. Alternatively, sliding can be paused or resumed by pressing »a« on the keyboard. Sliding is paused automatically as soon as the user starts navigating. You can disable these controls by specifying ```autoSlideStoppable: false``` in your reveal.js config. - -You can also override the slide duration for individual slides and fragments by using the ```data-autoslide``` attribute: - -```html -
-

After 2 seconds the first fragment will be shown.

-

After 10 seconds the next fragment will be shown.

-

Now, the fragment is displayed for 2 seconds before the next slide is shown.

-
-``` - -Whenever the auto-slide mode is resumed or paused the ```autoslideresumed``` and ```autoslidepaused``` events are fired. - - -### Keyboard Bindings - -If you're unhappy with any of the default keyboard bindings you can override them using the ```keyboard``` config option: - -```javascript -Reveal.configure({ - keyboard: { - 13: 'next', // go to the next slide when the ENTER key is pressed - 27: function() {}, // do something custom when ESC is pressed - 32: null // don't do anything when SPACE is pressed (i.e. disable a reveal.js default binding) - } -}); -``` - -### Lazy Loading - -When working on presentation with a lot of media or iframe content it's important to load lazily. Lazy loading means that reveal.js will only load content for the few slides nearest to the current slide. The number of slides that are preloaded is determined by the `viewDistance` configuration option. - -To enable lazy loading all you need to do is change your "src" attributes to "data-src" as shown below. This is supported for image, video, audio and iframe elements. Lazy loaded iframes will also unload when the containing slide is no longer visible. - -```html -
- - - -
-``` - - -### API - -The ``Reveal`` object exposes a JavaScript API for controlling navigation and reading state: - -```javascript -// Navigation -Reveal.slide( indexh, indexv, indexf ); -Reveal.left(); -Reveal.right(); -Reveal.up(); -Reveal.down(); -Reveal.prev(); -Reveal.next(); -Reveal.prevFragment(); -Reveal.nextFragment(); - -// Toggle presentation states, optionally pass true/false to force on/off -Reveal.toggleOverview(); -Reveal.togglePause(); -Reveal.toggleAutoSlide(); - -// Change a config value at runtime -Reveal.configure({ controls: true }); - -// Returns the present configuration options -Reveal.getConfig(); - -// Fetch the current scale of the presentation -Reveal.getScale(); - -// Retrieves the previous and current slide elements -Reveal.getPreviousSlide(); -Reveal.getCurrentSlide(); - -Reveal.getIndices(); // { h: 0, v: 0 } } -Reveal.getProgress(); // 0-1 -Reveal.getTotalSlides(); - -// State checks -Reveal.isFirstSlide(); -Reveal.isLastSlide(); -Reveal.isOverview(); -Reveal.isPaused(); -Reveal.isAutoSliding(); -``` - -### Slide Changed Event - -A 'slidechanged' event is fired each time the slide is changed (regardless of state). The event object holds the index values of the current slide as well as a reference to the previous and current slide HTML nodes. - -Some libraries, like MathJax (see [#226](https://github.com/hakimel/reveal.js/issues/226#issuecomment-10261609)), get confused by the transforms and display states of slides. Often times, this can be fixed by calling their update or render function from this callback. - -```javascript -Reveal.addEventListener( 'slidechanged', function( event ) { - // event.previousSlide, event.currentSlide, event.indexh, event.indexv -} ); -``` - -### Presentation State - -The presentation's current state can be fetched by using the `getState` method. A state object contains all of the information required to put the presentation back as it was when `getState` was first called. Sort of like a snapshot. It's a simple object that can easily be stringified and persisted or sent over the wire. - -```javascript -Reveal.slide( 1 ); -// we're on slide 1 - -var state = Reveal.getState(); - -Reveal.slide( 3 ); -// we're on slide 3 - -Reveal.setState( state ); -// we're back on slide 1 -``` - -### Slide States - -If you set ``data-state="somestate"`` on a slide ``
``, "somestate" will be applied as a class on the document element when that slide is opened. This allows you to apply broad style changes to the page based on the active slide. - -Furthermore you can also listen to these changes in state via JavaScript: - -```javascript -Reveal.addEventListener( 'somestate', function() { - // TODO: Sprinkle magic -}, false ); -``` - -### Slide Backgrounds - -Slides are contained within a limited portion of the screen by default to allow them to fit any display and scale uniformly. You can apply full page backgrounds outside of the slide area by adding a ```data-background``` attribute to your ```
``` elements. Four different types of backgrounds are supported: color, image, video and iframe. Below are a few examples. - -```html -
-

All CSS color formats are supported, like rgba() or hsl().

-
-
-

This slide will have a full-size background image.

-
-
-

This background image will be sized to 100px and repeated.

-
-
-

Video. Multiple sources can be defined using a comma separated list. Video will loop when the data-background-video-loop attribute is provided.

-
-
-

Embeds a web page as a background. Note that the page won't be interactive.

-
-``` - -Backgrounds transition using a fade animation by default. This can be changed to a linear sliding transition by passing ```backgroundTransition: 'slide'``` to the ```Reveal.initialize()``` call. Alternatively you can set ```data-background-transition``` on any section with a background to override that specific transition. - - -### Parallax Background - -If you want to use a parallax scrolling background, set the first two config properties below when initializing reveal.js (the other two are optional). - -```javascript -Reveal.initialize({ - - // Parallax background image - parallaxBackgroundImage: '', // e.g. "https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg" - - // Parallax background size - parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" - currently only pixels are supported (don't use % or auto) - - // Amount of pixels to move the parallax background per slide step, - // a value of 0 disables movement along the given axis - // These are optional, if they aren't specified they'll be calculated automatically - parallaxBackgroundHorizontal: 200, - parallaxBackgroundVertical: 50 - -}); -``` - -Make sure that the background size is much bigger than screen size to allow for some scrolling. [View example](http://lab.hakim.se/reveal-js/?parallaxBackgroundImage=https%3A%2F%2Fs3.amazonaws.com%2Fhakim-static%2Freveal-js%2Freveal-parallax-1.jpg¶llaxBackgroundSize=2100px%20900px). - - - -### Slide Transitions -The global presentation transition is set using the ```transition``` config value. You can override the global transition for a specific slide by using the ```data-transition``` attribute: - -```html -
-

This slide will override the presentation transition and zoom!

-
- -
-

Choose from three transition speeds: default, fast or slow!

-
-``` - -You can also use different in and out transitions for the same slide: - -```html -
- The train goes on … -
-
- and on … -
-
- and stops. -
-
- (Passengers entering and leaving) -
-
- And it starts again. -
-``` - - -Note that this does not work with the page and cube transitions. - - -### Internal links - -It's easy to link between slides. The first example below targets the index of another slide whereas the second targets a slide with an ID attribute (```
```): - -```html -Link -Link -``` - -You can also add relative navigation links, similar to the built in reveal.js controls, by appending one of the following classes on any element. Note that each element is automatically given an ```enabled``` class when it's a valid navigation route based on the current slide. - -```html - - - - - - -``` - - -### Fragments -Fragments are used to highlight individual elements on a slide. Every element with the class ```fragment``` will be stepped through before moving on to the next slide. Here's an example: http://lab.hakim.se/reveal-js/#/fragments - -The default fragment style is to start out invisible and fade in. This style can be changed by appending a different class to the fragment: - -```html -
-

grow

-

shrink

-

fade-out

-

visible only once

-

blue only once

-

highlight-red

-

highlight-green

-

highlight-blue

-
-``` - -Multiple fragments can be applied to the same element sequentially by wrapping it, this will fade in the text on the first step and fade it back out on the second. - -```html -
- - I'll fade in, then out - -
-``` - -The display order of fragments can be controlled using the ```data-fragment-index``` attribute. - -```html -
-

Appears last

-

Appears first

-

Appears second

-
-``` - -### Fragment events - -When a slide fragment is either shown or hidden reveal.js will dispatch an event. - -Some libraries, like MathJax (see #505), get confused by the initially hidden fragment elements. Often times this can be fixed by calling their update or render function from this callback. - -```javascript -Reveal.addEventListener( 'fragmentshown', function( event ) { - // event.fragment = the fragment DOM element -} ); -Reveal.addEventListener( 'fragmenthidden', function( event ) { - // event.fragment = the fragment DOM element -} ); -``` - -### Code syntax highlighting - -By default, Reveal is configured with [highlight.js](http://softwaremaniacs.org/soft/highlight/en/) for code syntax highlighting. Below is an example with clojure code that will be syntax highlighted. When the `data-trim` attribute is present surrounding whitespace is automatically removed. - -```html -
-

-(def lazy-fib
-  (concat
-   [0 1]
-   ((fn rfib [a b]
-        (lazy-cons (+ a b) (rfib b (+ a b)))) 0 1)))
-	
-
-``` - -### Slide number -If you would like to display the page number of the current slide you can do so using the ```slideNumber``` configuration value. - -```javascript -// Shows the slide number using default formatting -Reveal.configure({ slideNumber: true }); - -// Slide number formatting can be configured using these variables: -// h: current slide's horizontal index -// v: current slide's vertical index -// c: current slide index (flattened) -// t: total number of slides (flattened) -Reveal.configure({ slideNumber: 'c / t' }); - -``` - - -### Overview mode - -Press "Esc" or "o" keys to toggle the overview mode on and off. While you're in this mode, you can still navigate between slides, -as if you were at 1,000 feet above your presentation. The overview mode comes with a few API hooks: - -```javascript -Reveal.addEventListener( 'overviewshown', function( event ) { /* ... */ } ); -Reveal.addEventListener( 'overviewhidden', function( event ) { /* ... */ } ); - -// Toggle the overview mode programmatically -Reveal.toggleOverview(); -``` - -### Fullscreen mode -Just press »F« on your keyboard to show your presentation in fullscreen mode. Press the »ESC« key to exit fullscreen mode. - - -### Embedded media -Embedded HTML5 `