Files
FYS-STK4155/doc/LectureNotes/.ipynb_checkpoints/book-checkpoint.ipynb
T
2018-01-27 10:10:34 -05:00

264 KiB

Data Analysis and Machine Learning

Morten Hjorth-Jensen, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

Date: Jan 27, 2018

Copyright 1999-2018, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license

What is Machine Learning?

Machine learning is the science of giving computers the ability to learn without being explicitly programmed. The idea is that there exist generic algorithms which can be used to find patterns in a broad class of data sets without having to write code specifically for each problem. The algorithm will build its own logic based on the data.

Machine learning is a subfield of computer science, and is closely related to computational statistics. It evolved from the study of pattern recognition in artificial intelligence (AI) research, and has made contributions to AI tasks like computer vision, natural language processing and speech recognition. It has also, especially in later years, found applications in a wide variety of other areas, including bioinformatics, economy, physics, finance and marketing.

Types of Machine Learning

The approaches to machine learning are many, but are often split into two main categories. In supervised learning we know the answer to a problem, and let the computer deduce the logic behind it. On the other hand, unsupervised learning is a method for finding patterns and relationship in data sets without any prior knowledge of the system. Some authours also operate with a third category, namely reinforcement learning. This is a paradigm of learning inspired by behavioural psychology, where learning is achieved by trial-and-error, solely from rewards and punishment.

Another way to categorize machine learning tasks is to consider the desired output of a system. Some of the most common tasks are:

  • Classification: Outputs are divided into two or more classes. The goal is to produce a model that assigns inputs into one of these classes. An example is to identify digits based on pictures of hand-written ones. Classification is typically supervised learning.

  • Regression: Finding a functional relationship between an input data set and a reference data set. The goal is to construct a function that maps input data to continuous output values.

  • Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning.

Different algorithms

In this course we will build our machine learning approach on a statistical foundation, with elements from data analysis, stochastic processes etc before we proceed with the following machine learning algorithms

  1. Linear regression and its variants

  2. Decision tree algorithms, from simpler to more complex ones

  3. Nearest neighbors models

  4. Bayesian statistics

  5. Support vector machines and finally various variants of

  6. Artifical neural networks

Before we proceed however, there are several practicalities with data analysis and software tools we would like to present. These tools will help us in our understanding of various machine learning algorithms.

Our emphasis here is on understanding the mathematical aspects of different algorithms, however, where possible we will emphasize the importance of using available software.

Software and needed installations

We will make intensive use of python as programming language and the myriad of available libraries. Furthermore, you will find IPython/Jupyter notebooks invaluable in your work. You can run R codes in the Jupyter/IPython notebooks, with the immediate benefit of visualizing your data.

If you have Python installed (we recommend Python3) and you feel pretty familiar with installing different packages, we recommend that you install the following Python packages via pip as

  1. pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow

For Python3, replace pip with pip3.

For OSX users we recommend also, after having installed Xcode, to install brew. Brew allows for a seamless installation of additional software via for example

  1. brew install python3

For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution you can use pip as well and simply install Python as

  1. sudo apt-get install python3 (or python for pyhton2.7)

etc etc.

Python installers

If you don't want to perform these operations separately, we recommend two widely used distrubutions which set up all relevant dependencies for Python, namely

  1. Anaconda Anaconda is an open source distribution of the Python and R programming languages for large-scale data processing, predictive analytics, and scientific computing, that aims to simplify package management and deployment. Package versions are managed by the package management system conda

  2. Enthought canopy is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license.

Installing R, C++, cython or Julia

You will also find it convenient to utilize R. Jupyter/Ipython notebook allows you run R code interactively in your browser. The software library R is tuned to statistically analysis and allows for an easy usage of the tools we will discuss in these texts.

To install R with Jupyter notebook following the link here

Installing R, C++, cython or Julia

For the C++ affecianodas, Jupyter/IPython notebook allows you also to install C++ and run codes written in this language interactively in the browser. Since we will emphasize writing many of the algorithms yourself, you can thus opt for either Python or C++ as programming languages.

To add more entropy, cython can also be used when running your notebooks. It means that Python with the Jupyter/IPython notebook setup allows you to integrate widely popular softwares and tools for scientific computing. With its versatility, including symbolic operations, Python offers a unique computational environment. Your Jupyter/IPython notebook can easily be converted into a nicely rendered PDF file or a Latex file for further processing. For example, convert to latex as

In [1]:
jupyter nbconvert filename.ipynb --to latex

If you use the light mark-up language doconce you can convert a standard ascii text file into various HTML formats, ipython notebooks, latex files, pdf files etc.

Introduction to Jupyter notebook and available tools

In [2]:
%matplotlib inline

import numpy as np
import matplotlib.pyplot as plt
from scipy import sparse
import pandas as pd
from IPython.display import display
eye = np.eye(4)
print(eye)
sparse_mtx = sparse.csr_matrix(eye)
print(sparse_mtx)
x = np.linspace(-10,10,100)
y = np.sin(x)
plt.plot(x,y,marker='x')
plt.show()
data = {'Name': ["John", "Anna", "Peter", "Linda"], 'Location': ["Nairobi", "Napoli", "London", "Buenos Aires"], 'Age':[51, 21, 34, 45]}
data_pandas = pd.DataFrame(data)
display(data_pandas)

Representing data, more examples

In [3]:
import numpy as np
import matplotlib.pyplot as plt
from scipy import sparse
import pandas as pd
from IPython.display import display
import mglearn
import sklearn
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
x, y = mglearn.datasets.make_wave(n_samples=100)
line = np.linspace(-3,3,1000,endpoint=False).reshape(-1,1)
reg = DecisionTreeRegressor(min_samples_split=3).fit(x,y)
plt.plot(line, reg.predict(line), label="decision tree")
regline = LinearRegression().fit(x,y)
plt.plot(line, regline.predict(line), label= "Linear Rgression")
plt.show()

Predator-Prey model from ecology

The population dynamics of a simple predator-prey system is a classical example shown in many biology textbooks when ecological systems are discussed. The system contains all elements of the scientific method:

  • The set up of a specific hypothesis combined with

  • the experimental methods needed (one can study existing data or perform experiments)

  • analyzing and interpreting the data and performing further experiments if needed

  • trying to extract general behaviors and extract eventual laws or patterns

  • develop mathematical relations for the uncovered regularities/laws and test these by per forming new experiments

Case study from Hudson bay

Lots of data about populations of hares and lynx collected from furs in Hudson Bay, Canada, are available. It is known that the populations oscillate. Why? Here we start by

  1. plotting the data

  2. derive a simple model for the population dynamics

  3. (fitting parameters in the model to the data)

  4. using the model predict the evolution other predator-pray systems

Hudson bay data

Most mammalian predators rely on a variety of prey, which complicates mathematical modeling; however, a few predators have become highly specialized and seek almost exclusively a single prey species. An example of this simplified predator-prey interaction is seen in Canadian northern forests, where the populations of the lynx and the snowshoe hare are intertwined in a life and death struggle.

One reason that this particular system has been so extensively studied is that the Hudson Bay company kept careful records of all furs from the early 1800s into the 1900s. The records for the furs collected by the Hudson Bay company showed distinct oscillations (approximately 12 year periods), suggesting that these species caused almost periodic fluctuations of each other's populations. The table here shows data from 1900 to 1920.

Year Hares (x1000) Lynx (x1000)
1900 30.0 4.0
1901 47.2 6.1
1902 70.2 9.8
1903 77.4 35.2
1904 36.3 59.4
1905 20.6 41.7
1906 18.1 19.0
1907 21.4 13.0
1908 22.0 8.3
1909 25.4 9.1
1910 27.1 7.4
1911 40.3 8.0
1912 57 12.3
1913 76.6 19.5
1914 52.3 45.7
1915 19.5 51.1
1916 11.2 29.7
1917 7.6 15.8
1918 14.6 9.7
1919 16.2 10.1
1920 24.7 8.6

Plotting the data

In [4]:
import numpy as np
from  matplotlib import pyplot as plt

# Load in data file
data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1)
# Make arrays containing x-axis and hares and lynx populations
year = data[:,0]
hares = data[:,1]
lynx = data[:,2]

plt.plot(year, hares ,'b-+', year, lynx, 'r-o')
plt.axis([1900,1920,0, 100.0])
plt.xlabel(r'Year')
plt.ylabel(r'Numbers of hares and lynx ')
plt.legend(('Hares','Lynx'), loc='upper right')
plt.title(r'Population of hares and lynx from 1900-1920 (x1000)}')
plt.savefig('Hudson_Bay_data.pdf')
plt.savefig('Hudson_Bay_data.png')
plt.show()

Hares and lynx in Hudson bay from 1900 to 1920

Why now create a computer model for the hare and lynx populations?

We see from the plot that there are indeed fluctuations. We would like to create a mathematical model that explains these population fluctuations. Ecologists have predicted that in a simple predator-prey system that a rise in prey population is followed (with a lag) by a rise in the predator population. When the predator population is sufficiently high, then the prey population begins dropping. After the prey population falls, then the predator population falls, which allows the prey population to recover and complete one cycle of this interaction. Thus, we see that qualitatively oscillations occur. Can a mathematical model predict this? What causes cycles to slow or speed up? What affects the amplitude of the oscillation or do you expect to see the oscillations damp to a stable equilibrium? The models tend to ignore factors like climate and other complicating factors. How significant are these?

  • We see oscillations in the data

  • What causes cycles to slow or speed up?

  • What affects the amplitude of the oscillation or do you expect to see the oscillations damp to a stable equilibrium?

  • With a model we can better understand the data

  • More important: we can understand the ecology dynamics of predator-pray populations

The traditional (top-down) approach

The classical way (in all books) is to present the Lotka-Volterra equations:


\begin{align*}
\frac{dH}{dt} &= H(a - b L)\\
\frac{dL}{dt} &= - L(d - c  H)
\end{align*}

Here,

  • H is the number of preys

  • L the number of predators

  • a, b, d, c are parameters

Most books quickly establish the model and then use considerable space on discussing the qualitative properties of this nonlinear system of ODEs (which cannot be solved)

Basic mathematics notation

  • Time points: t_0,t_1,\ldots,t_m

  • Uniform distribution of time points: t_n=n\Delta t

  • H^n: population of hares at time t_n

  • L^n: population of lynx at time t_n

  • We want to model the changes in populations, \Delta H=H^{n+1}-H^n and \Delta L=L^{n+1}-L^n during a general time interval [t_{n+1},t_n] of length \Delta t=t_{n+1}-t_n

Basic dynamics of the population of hares

The population of hares evolves due to births and deaths exactly as a bacteria population:


\Delta H = a \Delta t H^n

However, hares have an additional loss in the population because they are eaten by lynx. All the hares and lynx can form H\cdot L pairs in total. When such pairs meet during a time interval \Delta t, there is some small probablity that the lynx will eat the hare. So in fraction b\Delta t HL, the lynx eat hares. This loss of hares must be accounted for. Subtracted in the equation for hares:


\Delta H = a\Delta t H^n - b \Delta t H^nL^n

Basic dynamics of the population of lynx

We assume that the primary growth for the lynx population depends on sufficient food for raising lynx kittens, which implies an adequate source of nutrients from predation on hares. Thus, the growth of the lynx population does not only depend of how many lynx there are, but on how many hares they can eat. In a time interval \Delta t HL hares and lynx can meet, and in a fraction b\Delta t HL the lynx eats the hare. All of this does not contribute to the growth of lynx, again just a fraction of b\Delta t HL that we write as d\Delta t HL. In addition, lynx die just as in the population dynamics with one isolated animal population, leading to a loss -c\Delta t L.

The accounting of lynx then looks like


\Delta L = d\Delta t H^nL^n - c\Delta t L^n

Evolution equations

By writing up the definition of \Delta H and \Delta L, and putting all assumed known terms H^n and L^n on the right-hand side, we have


H^{n+1} = H^n + a\Delta t H^n - b\Delta t H^n L^n

L^{n+1} = L^n + d\Delta t H^nL^n - c\Delta t L^n

Note:

  • These equations are ready to be implemented!

  • But to start, we need H^0 and L^0 (which we can get from the data)

  • We also need values for a, b, d, c

Adapt the model to the Hudson Bay case

  • As always, models tend to be general - as here, applicable to "all" predator-pray systems

  • The critical issue is whether the interaction between hares and lynx is sufficiently well modeled by \hbox{const}HL

  • The parameters a, b, d, and c must be estimated from data

  • Measure time in years

  • t_0=1900, t_m=1920

The program

In [5]:
import numpy as np
import matplotlib.pyplot as plt

def solver(m, H0, L0, dt, a, b, c, d, t0):
    """Solve the difference equations for H and L over m years
    with time step dt (measured in years."""

    num_intervals = int(m/float(dt))
    t = np.linspace(t0, t0 + m, num_intervals+1)
    H = np.zeros(t.size)
    L = np.zeros(t.size)

    print('Init:', H0, L0, dt)
    H[0] = H0
    L[0] = L0

    for n in range(0, len(t)-1):
        H[n+1] = H[n] + a*dt*H[n] - b*dt*H[n]*L[n]
        L[n+1] = L[n] + d*dt*H[n]*L[n] - c*dt*L[n]
    return H, L, t

# Load in data file
data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1)
# Make arrays containing x-axis and hares and lynx populations
t_e = data[:,0]
H_e = data[:,1]
L_e = data[:,2]

# Simulate using the model
H, L, t = solver(m=20, H0=34.91, L0=3.857, dt=0.1,
                 a=0.4807, b=0.02482, c=0.9272, d=0.02756,
                 t0=1900)

# Visualize simulations and data
plt.plot(t_e, H_e, 'b-+', t_e, L_e, 'r-o', t, H, 'm--', t, L, 'k--')
plt.xlabel('Year')
plt.ylabel('Numbers of hares and lynx')
plt.axis([1900, 1920, 0, 140])
plt.title(r'Population of hares and lynx 1900-1920 (x1000)')
plt.legend(('H_e', 'L_e', 'H', 'L'), loc='upper left')
plt.savefig('Hudson_Bay_sim.pdf')
plt.savefig('Hudson_Bay_sim.png')
plt.show()

The plot

If we perform a least-square fitting, we can find optimal values for the parameters a, b, d, c. The optimal parameters are a=0.4807, b=0.02482, d=0.9272 and c=0.02756. These parameters result in a slightly modified initial conditions, namely H(0) = 34.91 and L(0)=3.857. With these parameters we are now ready to solve the equations and plot these data together with the experimental values.

Linear regression in Python

In [6]:
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display
import sklearn
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor


data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1)
x = data[:,0]
y = data[:,1]
line = np.linspace(1900,1920,1000,endpoint=False).reshape(-1,1)
reg = DecisionTreeRegressor(min_samples_split=3).fit(x.reshape(-1,1),y.reshape(-1,1))
plt.plot(line, reg.predict(line), label="decision tree")
regline = LinearRegression().fit(x.reshape(-1,1),y.reshape(-1,1))
plt.plot(line, regline.predict(line), label= "Linear Regression")
plt.plot(x, y, label= "Linear Regression")
plt.show()

Linear Least squares in R

    HudsonBay = read.csv("src/Hudson_Bay.csv",header=T)
    fix(HudsonBay)
    dim(HudsonBay)
    names(HudsonBay)
    plot(HudsonBay$Year, HudsonBay$Hares..x1000.)
    attach(HudsonBay)
    plot(Year, Hares..x1000.)
    plot(Year, Hares..x1000., col="red", varwidth=T, xlab="Years", ylab="Haresx 1000")
    summary(HudsonBay)
    summary(Hares..x1000.)
    library(MASS)
    library(ISLR)
    scatter.smooth(x=Year, y = Hares..x1000.)
    linearMod = lm(Hares..x1000. ~ Year)
    print(linearMod)
    summary(linearMod)
    plot(linearMod)
    confint(linearMod)
    predict(linearMod,data.frame(Year=c(1910,1914,1920)),interval="confidence")

Non-Linear Least squares in R

    set.seed(1485)
    len = 24
    x = runif(len)
    y = x^3+rnorm(len, 0,0.06)
    ds = data.frame(x = x, y = y)
    str(ds)
    plot( y ~ x, main ="Known cubic with noise")
    s  = seq(0,1,length =100)
    lines(s, s^3, lty =2, col ="green")
    m = nls(y ~ I(x^power), data = ds, start = list(power=1), trace = T)
    class(m)
    summary(m)
    power = round(summary(m)$coefficients[1], 3)
    power.se = round(summary(m)$coefficients[2], 3)
    plot(y ~ x, main = "Fitted power model", sub = "Blue: fit; green: known")
    s = seq(0, 1, length = 100)
    lines(s, s^3, lty = 2, col = "green")
    lines(s, predict(m, list(x = s)), lty = 1, col = "blue")
    text(0, 0.5, paste("y =x^ (", power, " +/- ", power.se, ")", sep = ""), pos = 4)

Important Matrix and vector handling packages

The Numerical Recipes codes have been rewritten in Fortran 90/95 and C/C++ by us. The original source codes are taken from the widely used software package LAPACK, which follows two other popular packages developed in the 1970s, namely EISPACK and LINPACK.

  • LINPACK: package for linear equations and least square problems.

  • LAPACK:package for solving symmetric, unsymmetric and generalized eigenvalue problems. From LAPACK's website http://www.netlib.org it is possible to download for free all source codes from this library. Both C/C++ and Fortran versions are available.

  • BLAS (I, II and III): (Basic Linear Algebra Subprograms) are routines that provide standard building blocks for performing basic vector and matrix operations. Blas I is vector operations, II vector-matrix operations and III matrix-matrix operations. Highly parallelized and efficient codes, all available for download from http://www.netlib.org.

Add python material on linear algebra and array handling, text on numpy etc

Basic Matrix Features

Matrix properties reminder


\mathbf{A} =
      \begin{bmatrix} a_{11} & a_{12} & a_{13} & a_{14} \\
                                 a_{21} & a_{22} & a_{23} & a_{24} \\
                                   a_{31} & a_{32} & a_{33} & a_{34} \\
                                  a_{41} & a_{42} & a_{43} & a_{44}
             \end{bmatrix}\qquad
\mathbf{I} =
      \begin{bmatrix} 1 & 0 & 0 & 0 \\
                                 0 & 1 & 0 & 0 \\
                                 0 & 0 & 1 & 0 \\
                                 0 & 0 & 0 & 1
             \end{bmatrix}

Basic Matrix Features

The inverse of a matrix is defined by


\mathbf{A}^{-1} \cdot \mathbf{A} = I

Basic Matrix Features

Matrix Properties Reminder

Relations Name matrix elements
$A = A^{T}$ symmetric $a_{ij} = a_{ji}$
$A = \left (A^{T} \right )^{-1}$ real orthogonal $\sum_k a_{ik} a_{jk} = \sum_k a_{ki} a_{kj} = \delta_{ij}$
$A = A^{ * }$ real matrix $a_{ij} = a_{ij}^{ * }$
$A = A^{\dagger}$ hermitian $a_{ij} = a_{ji}^{ * }$
$A = \left (A^{\dagger} \right )^{-1}$ unitary $\sum_k a_{ik} a_{jk}^{ * } = \sum_k a_{ki}^{ * } a_{kj} = \delta_{ij}$

Some famous Matrices

  • Diagonal if a_{ij}=0 for i\ne j

  • Upper triangular if a_{ij}=0 for i > j

  • Lower triangular if a_{ij}=0 for i < j

  • Upper Hessenberg if a_{ij}=0 for i > j+1

  • Lower Hessenberg if a_{ij}=0 for i < j+1

  • Tridiagonal if a_{ij}=0 for |i -j| > 1

  • Lower banded with bandwidth p: a_{ij}=0 for i > j+p

  • Upper banded with bandwidth p: a_{ij}=0 for i < j+p

  • Banded, block upper triangular, block lower triangular....

Basic Matrix Features

Some Equivalent Statements For an N\times N matrix \mathbf{A} the following properties are all equivalent

  • If the inverse of \mathbf{A} exists, \mathbf{A} is nonsingular.

  • The equation \mathbf{Ax}=0 implies \mathbf{x}=0.

  • The rows of \mathbf{A} form a basis of R^N.

  • The columns of \mathbf{A} form a basis of R^N.

  • \mathbf{A} is a product of elementary matrices.

  • 0 is not eigenvalue of \mathbf{A}.

Matrix Handling in C/C++, Static and Dynamical allocation

Static We have an N\times N matrix A with N=100 In C/C++ this would be defined as

       int N = 100;
       double A[100][100];
       //   initialize all elements to zero
       for(i=0 ; i < N ; i++) {
          for(j=0 ; j < N ; j++) {
             A[i][j] = 0.0;

Note the way the matrix is organized, row-major order.

Matrix Handling in C/C++

Row Major Order, Addition We have N\times N matrices A, B and C and we wish to evaluate A=B+C.


\mathbf{A}= \mathbf{B}\pm\mathbf{C}  \Longrightarrow a_{ij} = b_{ij}\pm c_{ij},

In C/C++ this would be coded like

       for(i=0 ; i < N ; i++) {
          for(j=0 ; j < N ; j++) {
             a[i][j] = b[i][j]+c[i][j]

Matrix Handling in C/C++

Row Major Order, Multiplication We have N\times N matrices A, B and C and we wish to evaluate A=BC.


\mathbf{A}=\mathbf{BC}   \Longrightarrow a_{ij} = \sum_{k=1}^{n} b_{ik}c_{kj},

In C/C++ this would be coded like

       for(i=0 ; i < N ; i++) {
          for(j=0 ; j < N ; j++) {
             for(k=0 ; k < N ; k++) {
                a[i][j]+=b[i][k]*c[k][j];

Dynamic memory allocation in C/C++

At least three possibilities in this course

  • Do it yourself

  • Use the functions provided in the library package lib.cpp

  • Use Armadillo http://arma.sourceforgenet (a C++ linear algebra library, discussion both here and at lab).

Matrix Handling in C/C++, Dynamic Allocation

Do it yourself

    int N;
    double **  A;
    A = new double*[N]
    for ( i = 0; i < N; i++)
        A[i] = new double[N];

Always free space when you don't need an array anymore.

    for ( i = 0; i < N; i++)
        delete[] A[i];
    delete[] A;
  • Armadillo is a C++ linear algebra library (matrix maths) aiming towards a good balance between speed and ease of use. The syntax is deliberately similar to Matlab.

  • Integer, floating point and complex numbers are supported, as well as a subset of trigonometric and statistics functions. Various matrix decompositions are provided through optional integration with LAPACK, or one of its high performance drop-in replacements (such as the multi-threaded MKL or ACML libraries).

  • A delayed evaluation approach is employed (at compile-time) to combine several operations into one and reduce (or eliminate) the need for temporaries. This is accomplished through recursive templates and template meta-programming.

  • Useful for conversion of research code into production environments, or if C++ has been decided as the language of choice, due to speed and/or integration capabilities.

  • The library is open-source software, and is distributed under a license that is useful in both open-source and commercial/proprietary contexts.

Armadillo, simple examples

    #include <iostream>
    #include <armadillo>
    
    using namespace std;
    using namespace arma;
    
    int main(int argc, char** argv)
      {
      mat A = randu<mat>(5,5);
      mat B = randu<mat>(5,5);
    
      cout << A*B << endl;
    
      return 0;

Armadillo, how to compile and install

For people using Ubuntu, Debian, Linux Mint, simply go to the synaptic package manager and install armadillo from there. You may have to install Lapack as well. For Mac and Windows users, follow the instructions from the webpage http://arma.sourceforge.net. To compile, use for example (linux/ubuntu)

    c++ -O2 -o program.x program.cpp  -larmadillo -llapack -lblas

where the -l option indicates the library you wish to link to.

For OS X users you may have to declare the paths to the include files and the libraries as

    c++ -O2 -o program.x program.cpp  -L/usr/local/lib -I/usr/local/include -larmadillo -llapack -lblas

Armadillo, simple examples

    #include <iostream>
    #include "armadillo"
    using namespace arma;
    using namespace std;
    
    int main(int argc, char** argv)
      {
      // directly specify the matrix size (elements are uninitialised)
      mat A(2,3);
      // .n_rows = number of rows    (read only)
      // .n_cols = number of columns (read only)
      cout << "A.n_rows = " << A.n_rows << endl;
      cout << "A.n_cols = " << A.n_cols << endl;
      // directly access an element (indexing starts at 0)
      A(1,2) = 456.0;
      A.print("A:");
      // scalars are treated as a 1x1 matrix,
      // hence the code below will set A to have a size of 1x1
      A = 5.0;
      A.print("A:");
      // if you want a matrix with all elements set to a particular value
      // the .fill() member function can be used
      A.set_size(3,3);
      A.fill(5.0);  A.print("A:");

Armadillo, simple examples

      mat B;
    
      // endr indicates "end of row"
      B << 0.555950 << 0.274690 << 0.540605 << 0.798938 << endr
        << 0.108929 << 0.830123 << 0.891726 << 0.895283 << endr
        << 0.948014 << 0.973234 << 0.216504 << 0.883152 << endr
        << 0.023787 << 0.675382 << 0.231751 << 0.450332 << endr;
    
      // print to the cout stream
      // with an optional string before the contents of the matrix
      B.print("B:");
    
      // the << operator can also be used to print the matrix
      // to an arbitrary stream (cout in this case)
      cout << "B:" << endl << B << endl;
      // save to disk
      B.save("B.txt", raw_ascii);
      // load from disk
      mat C;
      C.load("B.txt");
      C += 2.0 * B;
      C.print("C:");

Armadillo, simple examples

      // submatrix types:
      //
      // .submat(first_row, first_column, last_row, last_column)
      // .row(row_number)
      // .col(column_number)
      // .cols(first_column, last_column)
      // .rows(first_row, last_row)
    
      cout << "C.submat(0,0,3,1) =" << endl;
      cout << C.submat(0,0,3,1) << endl;
    
      // generate the identity matrix
      mat D = eye<mat>(4,4);
    
      D.submat(0,0,3,1) = C.cols(1,2);
      D.print("D:");
    
      // transpose
      cout << "trans(B) =" << endl;
      cout << trans(B) << endl;
    
      // maximum from each column (traverse along rows)
      cout << "max(B) =" << endl;
      cout << max(B) << endl;

Armadillo, simple examples

      // maximum from each row (traverse along columns)
      cout << "max(B,1) =" << endl;
      cout << max(B,1) << endl;
      // maximum value in B
      cout << "max(max(B)) = " << max(max(B)) << endl;
      // sum of each column (traverse along rows)
      cout << "sum(B) =" << endl;
      cout << sum(B) << endl;
      // sum of each row (traverse along columns)
      cout << "sum(B,1) =" << endl;
      cout << sum(B,1) << endl;
      // sum of all elements
      cout << "sum(sum(B)) = " << sum(sum(B)) << endl;
      cout << "accu(B)     = " << accu(B) << endl;
      // trace = sum along diagonal
      cout << "trace(B)    = " << trace(B) << endl;
      // random matrix -- values are uniformly distributed in the [0,1] interval
      mat E = randu<mat>(4,4);
      E.print("E:");

Armadillo, simple examples

      // row vectors are treated like a matrix with one row
      rowvec r;
      r << 0.59499 << 0.88807 << 0.88532 << 0.19968;
      r.print("r:");
    
      // column vectors are treated like a matrix with one column
      colvec q;
      q << 0.81114 << 0.06256 << 0.95989 << 0.73628;
      q.print("q:");
    
      // dot or inner product
      cout << "as_scalar(r*q) = " << as_scalar(r*q) << endl;
    
        // outer product
      cout << "q*r =" << endl;
      cout << q*r << endl;
    
    
      // sum of three matrices (no temporary matrices are created)
      mat F = B + C + D;
      F.print("F:");
    
        return 0;

Armadillo, simple examples

    #include <iostream>
    #include "armadillo"
    using namespace arma;
    using namespace std;
    
    int main(int argc, char** argv)
      {
      cout << "Armadillo version: " << arma_version::as_string() << endl;
    
      mat A;
    
      A << 0.165300 << 0.454037 << 0.995795 << 0.124098 << 0.047084 << endr
        << 0.688782 << 0.036549 << 0.552848 << 0.937664 << 0.866401 << endr
        << 0.348740 << 0.479388 << 0.506228 << 0.145673 << 0.491547 << endr
        << 0.148678 << 0.682258 << 0.571154 << 0.874724 << 0.444632 << endr
        << 0.245726 << 0.595218 << 0.409327 << 0.367827 << 0.385736 << endr;
    
      A.print("A =");
    
      // determinant
      cout << "det(A) = " << det(A) << endl;

Armadillo, simple examples

      // inverse
      cout << "inv(A) = " << endl << inv(A) << endl;
      double k = 1.23;
    
      mat    B = randu<mat>(5,5);
      mat    C = randu<mat>(5,5);
    
      rowvec r = randu<rowvec>(5);
      colvec q = randu<colvec>(5);
    
    
      // examples of some expressions
      // for which optimised implementations exist
      // optimised implementation of a trinary expression
      // that results in a scalar
      cout << "as_scalar( r*inv(diagmat(B))*q ) = ";
      cout << as_scalar( r*inv(diagmat(B))*q ) << endl;
    
      // example of an expression which is optimised
      // as a call to the dgemm() function in BLAS:
      cout << "k*trans(B)*C = " << endl << k*trans(B)*C;
    
        return 0;

Gaussian Elimination

We start with the linear set of equations


\mathbf{A}\mathbf{x} = \mathbf{w}.

We assume also that the matrix \mathbf{A} is non-singular and that the matrix elements along the diagonal satisfy a_{ii} \ne 0. Simple 4\times 4 example


\begin{bmatrix}
                           a_{11}& a_{12} &a_{13}& a_{14}\\
                           a_{21}& a_{22} &a_{23}& a_{24}\\
                           a_{31}& a_{32} &a_{33}& a_{34}\\
                           a_{41}& a_{42} &a_{43}& a_{44}\\
                      \end{bmatrix} \begin{bmatrix}
                           x_1\\
                           x_2\\
                           x_3 \\
                           x_4  \\
                      \end{bmatrix}
  =\begin{bmatrix}
                           w_1\\
                           w_2\\
                           w_3 \\
                           w_4\\
                      \end{bmatrix}.

Gaussian Elimination

or


a_{11}x_1 +a_{12}x_2 +a_{13}x_3 + a_{14}x_4=w_1 \nonumber

a_{21}x_1 + a_{22}x_2 + a_{23}x_3 + a_{24}x_4=w_2 \nonumber

a_{31}x_1 + a_{32}x_2 + a_{33}x_3 + a_{34}x_4=w_3 \nonumber

a_{41}x_1 + a_{42}x_2 + a_{43}x_3 + a_{44}x_4=w_4. \nonumber

Gaussian Elimination

The basic idea of Gaussian elimination is to use the first equation to eliminate the first unknown x_1 from the remaining n-1 equations. Then we use the new second equation to eliminate the second unknown x_2 from the remaining n-2 equations. With n-1 such eliminations we obtain a so-called upper triangular set of equations of the form


b_{11}x_1 +b_{12}x_2 +b_{13}x_3 + b_{14}x_4=y_1 \nonumber

b_{22}x_2 + b_{23}x_3 + b_{24}x_4=y_2 \nonumber

b_{33}x_3 + b_{34}x_4=y_3 \nonumber

b_{44}x_4=y_4. \nonumber
\label{eq:gaussbacksub} \tag{1}

We can solve this system of equations recursively starting from x_n (in our case x_4) and proceed with what is called a backward substitution.

Gaussian Elimination

This process can be expressed mathematically as


\begin{equation}
   x_m = \frac{1}{b_{mm}}\left(y_m-\sum_{k=m+1}^nb_{mk}x_k\right)\quad m=n-1,n-2,\dots,1.
\label{_auto1} \tag{2}
\end{equation}

To arrive at such an upper triangular system of equations, we start by eliminating the unknown x_1 for j=2,n. We achieve this by multiplying the first equation by a_{j1}/a_{11} and then subtract the result from the $j$th equation. We assume obviously that a_{11}\ne 0 and that \mathbf{A} is not singular.

Gaussian Elimination

Our actual 4\times 4 example reads after the first operation


\begin{bmatrix}
                           a_{11}& a_{12} &a_{13}& a_{14}\\
                           0& (a_{22}-\frac{a_{21}a_{12}}{a_{11}}) &(a_{23}-\frac{a_{21}a_{13}}{a_{11}}) & (a_{24}-\frac{a_{21}a_{14}}{a_{11}})\\
0& (a_{32}-\frac{a_{31}a_{12}}{a_{11}})& (a_{33}-\frac{a_{31}a_{13}}{a_{11}})& (a_{34}-\frac{a_{31}a_{14}}{a_{11}})\\
0&(a_{42}-\frac{a_{41}a_{12}}{a_{11}}) &(a_{43}-\frac{a_{41}a_{13}}{a_{11}}) & (a_{44}-\frac{a_{41}a_{14}}{a_{11}}) \\
                      \end{bmatrix} \begin{bmatrix}
                           x_1\\
                           x_2\\
                           x_3 \\
                           x_4  \\
                      \end{bmatrix} 
  =\begin{bmatrix}
                           y_1\\
                           w_2^{(2)}\\
                           w_3^{(2)} \\
                           w_4^{(2)}\\
                      \end{bmatrix},

or


b_{11}x_1 +b_{12}x_2 +b_{13}x_3 + b_{14}x_4=y_1 \nonumber

a^{(2)}_{22}x_2 + a^{(2)}_{23}x_3 + a^{(2)}_{24}x_4=w^{(2)}_2 \nonumber

a^{(2)}_{32}x_2 + a^{(2)}_{33}x_3 + a^{(2)}_{34}x_4=w^{(2)}_3 \nonumber

a^{(2)}_{42}x_2 + a^{(2)}_{43}x_3 + a^{(2)}_{44}x_4=w^{(2)}_4, \nonumber

\begin{equation} 
\label{_auto2} \tag{3}
\end{equation}

Gaussian Elimination

The new coefficients are


\begin{equation}
   b_{1k} = a_{1k}^{(1)} \quad k=1,\dots,n,
\label{_auto3} \tag{4}
\end{equation}

where each a_{1k}^{(1)} is equal to the original a_{1k} element. The other coefficients are


\begin{equation}
a_{jk}^{(2)} = a_{jk}^{(1)}-\frac{a_{j1}^{(1)}a_{1k}^{(1)}}{a_{11}^{(1)}} \quad j,k=2,\dots,n,
\label{_auto4} \tag{5}
\end{equation}

with a new right-hand side given by


\begin{equation}
y_{1}=w_1^{(1)}, \quad w_j^{(2)} =w_j^{(1)}-\frac{a_{j1}^{(1)}w_1^{(1)}}{a_{11}^{(1)}} \quad j=2,\dots,n.
\label{_auto5} \tag{6}
\end{equation}

We have also set w_1^{(1)}=w_1, the original vector element. We see that the system of unknowns x_1,\dots,x_n is transformed into an (n-1)\times (n-1) problem.

Gaussian Elimination

This step is called forward substitution. Proceeding with these substitutions, we obtain the general expressions for the new coefficients


\begin{equation}
   a_{jk}^{(m+1)} = a_{jk}^{(m)}-\frac{a_{jm}^{(m)}a_{mk}^{(m)}}{a_{mm}^{(m)}} \quad j,k=m+1,\dots,n,
\label{_auto6} \tag{7}
\end{equation}

with m=1,\dots,n-1 and a right-hand side given by


\begin{equation}
   w_j^{(m+1)} =w_j^{(m)}-\frac{a_{jm}^{(m)}w_m^{(m)}}{a_{mm}^{(m)}}\quad j=m+1,\dots,n.
\label{_auto7} \tag{8}
\end{equation}

This set of n-1 elimations leads us to an equations which is solved by back substitution. If the arithmetics is exact and the matrix \mathbf{A} is not singular, then the computed answer will be exact.

Even though the matrix elements along the diagonal are not zero, numerically small numbers may appear and subsequent divisions may lead to large numbers, which, if added to a small number may yield losses of precision. Suppose for example that our first division in (a_{22}-a_{21}a_{12}/a_{11}) results in -10^{-7} and that a_{22} is one. one. We are then adding 10^7+1. With single precision this results in 10^7.

Linear Algebra Methods

  • Gaussian elimination, O(2/3n^3) flops, general matrix

  • LU decomposition, upper triangular and lower tridiagonal matrices, O(2/3n^3) flops, general matrix. Get easily the inverse, determinant and can solve linear equations with back-substitution only, O(n^2) flops

  • Cholesky decomposition. Real symmetric or hermitian positive definite matrix, O(1/3n^3) flops.

  • Tridiagonal linear systems, important for differential equations. Normally positive definite and non-singular. O(8n) flops for symmetric. Special case of banded matrices.

  • Singular value decomposition

  • the QR method will be discussed in chapter 7 in connection with eigenvalue systems. O(4/3n^3) flops.

LU Decomposition

The LU decomposition method means that we can rewrite this matrix as the product of two matrices \mathbf{L} and \mathbf{U} where

Warning:
Output truncated. This notebook contains too many cells to display efficiently.