Files
FYS-STK4155/doc/LectureNotes/_build/jupyter_execute/week34.ipynb
T
2023-09-03 14:22:23 +02:00

445 KiB

Week 34: Introduction to the course, Logistics and Practicalities

Morten Hjorth-Jensen, Department of Physics and Center for Computing in Science Education, University of Oslo, Norway and Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University, USA

Date: Week 34, August 21-25, 2023

Overview of first week

  1. The sessions on Tuesdays and Wednesdays last four hours for each group (four groups in total) and will include lectures in a flipped mode (promoting active learning) and work on exercices and projects.

  2. The sessions will begin with lectures, discussions, questions and answers about the material to be covered every week. Videos and teaching material will be announced in due time.

  3. There are four groups:

  • Tuesdays 815am-12pm and 1215pm-4pm

  • Wednesdays 815am-12pm and 1215pm-4pm.

  1. On Thursdays we have a regular lecture. These lectures start at 1215pm and end at 2pm and serve the aims of giving an overview over various topics. These lectures will also be recorded.

The labs are also available till 6pm Tuesdays and Wednesdays. Videos and learning material with reading suggestions will be made available before each week starts.

Schedule first week

  • August 22: Presentation of the course, aims and content. Introduction to software and repetition of Python Programming, linear algebra and basic elements of statistics. Please select group.

  • August 23: Presentation of the course, aims and content. Introduction to software and repetition of Python Programming, linear algebra and basic elements of statistics. Please select group.

  • August 24: Lecture: Linear regression, examples and theory

Lectures and ComputerLab

  • The sessions on Tuesdays and Wednesdays last four hours and will include partly lectures in a flipped mode (promoting active learning) and work on exercices and projects.

  • Thursdays: regular lectures (12.15pm-2pm)

  • Weekly reading assignments and videos needed to solve projects and exercises.

  • Weekly exercises. You can hand in exercises if you want and get an extra score, see below.

  • Detailed lecture notes, exercises, all programs presented, projects etc can be found at the homepage of the course.

  • Weekly plans and all other information are on the official website. This info will also be conveyed via weekly emails.

  • No final exam, three projects that are graded and have to be approved.

Communication channels

  • Chat and communications via <canvas.uio.no>

  • Discord channel will be added asap

Course Format

  • Three compulsory projects. Electronic reports only using Canvas to hand in projects and git as version control software and GitHub for repository (or GitLab) of all your material.

  • Evaluation and grading: The three projects are graded and each counts 1/3 of the final mark. No final written or oral exam.

a. For the last project each group/participant submits a proposal or works with suggested (by us) proposals for the project.

b. If possible, we would like to organize the last project as a workshop where each group presents this to all other participants of the course

c. Based on feedback etc, each group finalizes the report and submits for grading.

  • Python is the default programming language, but feel free to use C/C++, Julia and/or Fortran or other programming languages. All source codes discussed during the lectures can be found at the webpage and github address of the course.

Teachers

Deadlines for projects (tentative)

  1. Project 1: October 9 (available September 4) graded with feedback)

  2. Project 2: November 6 (available October 6, graded with feedback)

  3. Project 3: December 11 (available November 10, graded with feedback)

Extra Credit (not mandatory), weekly exercise assignments, 10 in total (due Friday same week), 10% additional score. The extra credit assignments are due each Friday and can be uploaed to Canvas in your preferred format (although we prefer jupyter-notebooks). First assignment is for week 35. Each weekly exercise set counts 1%.

Grading

Grades are awarded on a scale from A to F, where A is the best grade and F is a fail. There are three projects which are graded and each project counts 1/3 of the final grade. The total score is thus the average from all three projects.

The final number of points is based on the average of all projects and the grade follows the following table:

  • 92-100 points: A

  • 77-91 points: B

  • 58-76 points: C

  • 46-57 points: D

  • 40-45 points: E

  • 0-39 points: F-failed

In addition you can get an extra 10% score for weekly assignments (10 in total and due each Friday). Each weekly assignment counts 1%.

Reading material

The lecture notes are collected as a jupyter-book at https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/intro.html.

In addition to the lecture notes, we recommend the books of Bishop, Hastie et al, Murphy and Goodfellow et al. We will follow these texts closely and the weekly reading assignments refer to these texts. The text by Hastie et al is also widely used in the Machine Learning community. Finally, we also recommend the hands-on text by Geron, see next slide for links.

Textbooks

Reading suggestions week 34

This week: Refresh linear algebra, GBC chapters 1 and 2. HTF chapters 2 and 3. Install scikit-learn. See lecture notes for week 34 at https://compphysics.github.io/MachineLearning/doc/web/course.html (these notes).

Prerequisites

Basic knowledge in programming and mathematics, with an emphasis on linear algebra. Knowledge of Python or/and C++ as programming languages is strongly recommended and experience with Jupiter notebook is recommended. Required courses are the equivalents to the University of Oslo mathematics courses MAT1100, MAT1110, MAT1120 and at least one of the corresponding computing and programming courses INF1000/INF1110 or MAT-INF1100/MAT-INF1100L/BIOS1100/KJM-INF1100. Most universities offer nowadays a basic programming course (often compulsory) where Python is the recurring programming language.

Topics covered in this course: Statistical analysis and optimization of data

The course has two central parts

  1. Statistical analysis and optimization of data

  2. Machine learning

These topics will be scattered thorughout the course and may not necessarily be taught separately. Rather, we will often take an approach (during the lectures and project/exercise sessions) where say elements from statistical data analysis are mixed with specific Machine Learning algorithms.

Statistical analysis and optimization of data

We plan to cover the following topics:

  • Basic concepts, expectation values, variance, covariance, correlation functions and errors;

  • Simpler models, binomial distribution, the Poisson distribution, simple and multivariate normal distributions;

  • Central elements of Bayesian statistics and modeling;

  • Gradient methods for data optimization;

  • Monte Carlo methods, Markov chains, Gibbs sampling and Metropolis-Hastings sampling (tentative);

  • Estimation of errors and resampling techniques such as the cross-validation, blocking, bootstrapping and jackknife methods;

  • Principal Component Analysis (PCA) and its mathematical foundation;

Machine Learning

  • Pre deep-learning revolution (2008 approx)

    • Linear Regression and Logistic Regression, classification and regression problems;

    • Bayesian linear and logistic regression, kernel regression;

    • Decisions trees, Random Forests, Bagging and Boosting methods;

    • Support vector machines (only survey);

    • Unsupervised learning and dimensionality reduction, from PCA to clustering;

  • Deep learning

    • Neural networks and deep learning;

    • Convolutional neural networks;

    • Recurrent neural networks;

    • Autoencoders

    • Generative methods with an emphasis on Boltzmann Machines, Variational Autoencoders and Generalized Adversarial Networks;

Hands-on demonstrations, exercises and projects aim at deepening your understanding of these topics.

and discussed at the lab sessions.

Other courses on Data science and Machine Learning at UiO

Other courses on Data science and Machine Learning at UiO, contn

Learning outcomes

This course aims at giving you insights and knowledge about many of the central algorithms used in Data Analysis and Machine Learning. The course is project based and through various numerical projects, normally three, you will be exposed to fundamental research problems in these fields, with the aim to reproduce state of the art scientific results. Both supervised and unsupervised methods will be covered. The emphasis is on a frequentist approach, although we will try to link it with a Bayesian approach as well. You will learn to develop and structure large codes for studying different cases where Machine Learning is applied to, get acquainted with computing facilities and learn to handle large scientific projects. A good scientific and ethical conduct is emphasized throughout the course. More specifically, after this course you will

  • Learn about basic data analysis, statistical analysis, Bayesian statistics, Monte Carlo sampling, data optimization and machine learning;

  • Be capable of extending the acquired knowledge to other systems and cases;

  • Have an understanding of central algorithms used in data analysis and machine learning;

  • Understand linear methods for regression and classification, from ordinary least squares, via Lasso and Ridge to Logistic regression;

  • Learn about neural networks and deep learning methods for supervised and unsupervised learning. Emphasis on feed forward neural networks, convolutional and recurrent neural networks;

  • Learn about about decision trees, random forests, bagging and boosting methods;

  • Learn about support vector machines and kernel transformations;

  • Reduction of data sets, from PCA to clustering;

  • Generative models

  • Work on numerical projects to illustrate the theory. The projects play a central role and you are expected to know modern programming languages like Python or C++ and/or Fortran (Fortran2003 or later) or Julia or other.

Introduction

Our emphasis throughout this series of lectures
is on understanding the mathematical aspects of different algorithms used in the fields of data analysis and machine learning.

However, where possible we will emphasize the importance of using available software. We start thus with a hands-on and top-down approach to machine learning. The aim is thus to start with relevant data or data we have produced and use these to introduce statistical data analysis concepts and machine learning algorithms before we delve into the algorithms themselves. The examples we will use in the beginning, start with simple polynomials with random noise added. We will use the Python software package Scikit-Learn and introduce various machine learning algorithms to make fits of the data and predictions. We move thereafter to more interesting cases such as data from say experiments (below we will look at experimental nuclear binding energies as an example). These are examples where we can easily set up the data and then use machine learning algorithms included in for example Scikit-Learn.

These examples will serve us the purpose of getting started. Furthermore, they allow us to catch more than two birds with a stone. They will allow us to bring in some programming specific topics and tools as well as showing the power of various Python libraries for machine learning and statistical data analysis.

Although we have projects where you write your own codes, we will also focus on two specific Python packages for Machine Learning, Scikit-Learn and Tensorflow with Keras (see below for links etc). Moreover, the examples we introduce will serve as inputs to many of our discussions later, as well as allowing you to set up models and produce your own data and get started with programming.

AI/ML and some statements you may have heard (and what do they mean?)

  1. Fei-Fei Li on ImageNet: map out the entire world of objects (The data that transformed AI research)

  2. Russell and Norvig in their popular textbook: relevant to any intellectual task; it is truly a universal field (Artificial Intelligence, A modern approach)

  3. Woody Bledsoe puts it more bluntly: in the long run, AI is the only science (quoted in Pamilla McCorduck, Machines who think)

If you wish to have a critical read on AI/ML from a societal point of view, see Kate Crawford's recent text Atlas of AI

Here: with AI/ML we intend a collection of machine learning methods with an emphasis on statistical learning and data analysis

What is Machine Learning?

Statistics, data science and machine learning form important fields of research in modern science. They describe how to learn and make predictions from data, as well as allowing us to extract important correlations about physical process and the underlying laws of motion in large data sets. The latter, big data sets, appear frequently in essentially all disciplines, from the traditional Science, Technology, Mathematics and Engineering fields to Life Science, Law, education research, the Humanities and the Social Sciences.

It has become more and more common to see research projects on big data in for example the Social Sciences where extracting patterns from complicated survey data is one of many research directions. Having a solid grasp of data analysis and machine learning is thus becoming central to scientific computing in many fields, and competences and skills within the fields of machine learning and scientific computing are nowadays strongly requested by many potential employers. The latter cannot be overstated, familiarity with machine learning has almost become a prerequisite for many of the most exciting employment opportunities, whether they are in bioinformatics, life science, physics or finance, in the private or the public sector. This author has had several students or met students who have been hired recently based on their skills and competences in scientific computing and data science, often with marginal knowledge of machine learning.

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. Many of the methods we will study are also strongly rooted in basic mathematics and physics research.

Ideally, machine learning represents 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. You should however always keep in mind that machines and algorithms are to a large extent developed by humans. The insights and knowledge we have about a specific system, play a central role when we develop a specific machine learning algorithm.

Machine learning is an extremely rich field, in spite of its young age. The increases we have seen during the last three decades in computational capabilities have been followed by developments of methods and techniques for analyzing and handling large date sets, relying heavily on statistics, computer science and mathematics. The field is rather new and developing rapidly. Popular software packages written in Python for machine learning like Scikit-learn, Tensorflow, PyTorch and Keras, all freely available at their respective GitHub sites, encompass communities of developers in the thousands or more. And the number of code developers and contributors keeps increasing. Not all the algorithms and methods can be given a rigorous mathematical justification, opening up thereby large rooms for experimenting and trial and error and thereby exciting new developments. However, a solid command of linear algebra, multivariate theory, probability theory, statistical data analysis, understanding errors and Monte Carlo methods are central elements in a proper understanding of many of algorithms and methods we will discuss.

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 behavioral 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.

Essential elements of ML

The methods we cover have three main topics in common, irrespective of whether we deal with supervised or unsupervised learning.

  • The first ingredient is normally our data set (which can be subdivided into training, validation and test data). Many find the most difficult part of using Machine Learning to be the set up of your data in a meaningful way.

  • The second item is a model which is normally a function of some parameters. The model reflects our knowledge of the system (or lack thereof). As an example, if we know that our data show a behavior similar to what would be predicted by a polynomial, fitting our data to a polynomial of some degree would then determin our model.

  • The last ingredient is a so-called cost/loss function (or error or risk function) which allows us to present an estimate on how good our model is in reproducing the data it is supposed to train.

An optimization/minimization problem

At the heart of basically all Machine Learning algorithms we will encounter so-called minimization or optimization algorithms. A large family of such methods are so-called gradient methods.

A Frequentist approach to data analysis

When you hear phrases like predictions and estimations and correlations and causations, what do you think of? May be you think of the difference between classifying new data points and generating new data points. Or perhaps you consider that correlations represent some kind of symmetric statements like if A is correlated with B, then B is correlated with A. Causation on the other hand is directional, that is if A causes B, B does not necessarily cause A.

These concepts are in some sense the difference between machine learning and statistics. In machine learning and prediction based tasks, we are often interested in developing algorithms that are capable of learning patterns from given data in an automated fashion, and then using these learned patterns to make predictions or assessments of newly given data. In many cases, our primary concern is the quality of the predictions or assessments, and we are less concerned about the underlying patterns that were learned in order to make these predictions.

In machine learning we normally use a so-called frequentist approach, where the aim is to make predictions and find correlations. We focus less on for example extracting a probability distribution function (PDF). The PDF can be used in turn to make estimations and find causations such as given A what is the likelihood of finding B.

What is a good model?

In science and engineering we often end up in situations where we want to infer (or learn) a quantitative model M for a given set of sample points \boldsymbol{X} \in [x_1, x_2,\dots x_N].

As we will see repeatedely in these lectures, we could try to fit these data points to a model given by a straight line, or if we wish to be more sophisticated to a more complex function.

The reason for inferring such a model is that it serves many useful purposes. On the one hand, the model can reveal information encoded in the data or underlying mechanisms from which the data were generated. For instance, we could discover important corelations that relate interesting physics interpretations.

In addition, it can simplify the representation of the given data set and help us in making predictions about future data samples.

A first important consideration to keep in mind is that inferring the correct model for a given data set is an elusive, if not impossible, task. The fundamental difficulty is that if we are not specific about what we mean by a correct model, there could easily be many different models that fit the given data set equally well.

What is a good model? Can we define it?

The central question is this: what leads us to say that a model is correct or optimal for a given data set? To make the model inference problem well posed, i.e., to guarantee that there is a unique optimal model for the given data, we need to impose additional assumptions or restrictions on the class of models considered. To this end, we should not be looking for just any model that can describe the data. Instead, we should look for a model M that is the best among a restricted class of models. In addition, to make the model inference problem computationally tractable, we need to specify how restricted the class of models needs to be. A common strategy is to start with the simplest possible class of models that is just necessary to describe the data or solve the problem at hand. More precisely, the model class should be rich enough to contain at least one model that can fit the data to a desired accuracy and yet be restricted enough that it is relatively simple to find the best model for the given data.

Thus, the most popular strategy is to start from the simplest class of models and increase the complexity of the models only when the simpler models become inadequate. For instance, if we work with a regression problem to fit a set of sample points, one may first try the simplest class of models, namely linear models, followed obviously by more complex models.

How to evaluate which model fits best the data is something we will come back to over and over again in these sets of lectures.

Software and needed installations

We will make extensive use of Python as programming language and its myriad of available libraries. You will find Jupyter notebooks invaluable in your work. You can run R codes in the Jupyter/IPython notebooks, with the immediate benefit of visualizing your data. You can also use compiled languages like C++, Rust, Julia, Fortran etc if you prefer. The focus in these lectures will be on Python.

If you have Python installed (we strongly 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, 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 and venture into the hassle of exploring how to set up dependencies and paths, we recommend two widely used distrubutions which set up all relevant dependencies for Python, namely

which 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.

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

Furthermore, Google's Colab is a free Jupyter notebook environment that requires no setup and runs entirely in the cloud. Try it out!

Useful Python libraries

Here we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there)

  • NumPy is a highly popular library for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays

  • The pandas library provides high-performance, easy-to-use data structures and data analysis tools

  • Xarray is a Python package that makes working with labelled multi-dimensional arrays simple, efficient, and fun!

  • Scipy (pronounced “Sigh Pie”) is a Python-based ecosystem of open-source software for mathematics, science, and engineering.

  • Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.

  • Autograd can automatically differentiate native Python and Numpy code. It can handle a large subset of Python's features, including loops, ifs, recursion and closures, and it can even take derivatives of derivatives of derivatives

  • JAX has now more or less replaced Autograd. JAX is Autograd and XLA, brought together for high-performance numerical computing and machine learning research. It provides composable transformations of Python+NumPy programs: differentiate, vectorize, parallelize, Just-In-Time compile to GPU/TPU, and more.

  • SymPy is a Python library for symbolic mathematics.

  • scikit-learn has simple and efficient tools for machine learning, data mining and data analysis

  • TensorFlow is a Python library for fast numerical computing created and released by Google

  • Keras is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano

  • And many more such as pytorch, Theano etc

Installing R, C++, cython or Julia

You will also find it convenient to utilize R. We will mainly use Python during our lectures and in various projects and exercises. Those of you already familiar with R should feel free to continue using R, keeping however an eye on the parallel Python set ups. Similarly, if you are a Python afecionado, feel free to explore R as well. Jupyter(Julia, Python and R) /Ipython notebook allows you to run R codes and Julia codes interactively in your browser. The software library R is really tailored for statistical data analysis and allows for an easy usage of the tools and algorithms we will discuss in these lectures.

To install R with Jupyter notebook follow the link here

Installing R, C++, cython, Numba etc

For the C++ aficionados, 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++ (or Fortran or other compiled languages) as programming languages.

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

    pycod jupyter nbconvert filename.ipynb --to latex 

And to add more versatility, the Python package SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python.

Finally, we recommend strongly using Autograd or JAX for automatic differentiation.

Numpy examples and Important Matrix and vector handling packages

There are several central software libraries for linear algebra and eigenvalue problems. Several of the more popular ones have been wrapped into ofter software packages like those from the widely used text Numerical Recipes. The original source codes in many of the available packages are often taken from the widely used software package LAPACK, which follows two other popular packages developed in the 1970s, namely EISPACK and LINPACK. We describe them shortly here.

  • 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.

Numpy and arrays

Numpy provides an easy way to handle arrays in Python. The standard way to import this library is as

In [1]:
import numpy as np

Here follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution,

In [2]:
n = 10
x = np.random.normal(size=n)
print(x)
[-0.75408649 -0.05177092 -0.07339251  1.49372893 -1.21467644  0.24712854
  0.67554302 -0.45143018  0.34212496  0.63262164]

We defined a vector x with n=10 elements with its values given by the Normal distribution N(0,1). Another alternative is to declare a vector as follows

In [3]:
import numpy as np
x = np.array([1, 2, 3])
print(x)
[1 2 3]

Here we have defined a vector with three elements, with x_0=1, x_1=2 and x_2=3. Note that both Python and C++ start numbering array elements from 0 and on. This means that a vector with n elements has a sequence of entities x_0, x_1, x_2, \dots, x_{n-1}. We could also let (recommended) Numpy to compute the logarithms of a specific array as

In [4]:
import numpy as np
x = np.log(np.array([4, 7, 8]))
print(x)
[1.38629436 1.94591015 2.07944154]

In the last example we used Numpy's unary function np.log. This function is highly tuned to compute array elements since the code is vectorized and does not require looping. We normaly recommend that you use the Numpy intrinsic functions instead of the corresponding log function from Python's math module. The looping is done explicitely by the np.log function. The alternative, and slower way to compute the logarithms of a vector would be to write

In [5]:
import numpy as np
from math import log
x = np.array([4, 7, 8])
for i in range(0, len(x)):
    x[i] = log(x[i])
print(x)
[1 1 2]

We note that our code is much longer already and we need to import the log function from the math module. The attentive reader will also notice that the output is [1, 1, 2]. Python interprets automagically our numbers as integers (like the automatic keyword in C++). To change this we could define our array elements to be double precision numbers as

In [6]:
import numpy as np
x = np.log(np.array([4, 7, 8], dtype = np.float64))
print(x)
[1.38629436 1.94591015 2.07944154]

or simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is

In [7]:
import numpy as np
x = np.log(np.array([4.0, 7.0, 8.0]))
print(x)
[1.38629436 1.94591015 2.07944154]

To check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the itemsize functionality (the array x is actually an object which inherits the functionalities defined in Numpy) as

In [8]:
import numpy as np
x = np.log(np.array([4.0, 7.0, 8.0]))
print(x.itemsize)
8

Matrices in Python

Having defined vectors, we are now ready to try out matrices. We can define a 3 \times 3 real matrix \boldsymbol{A} as (recall that we user lowercase letters for vectors and uppercase letters for matrices)

In [9]:
import numpy as np
A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
print(A)
[[1.38629436 1.94591015 2.07944154]
 [1.09861229 2.30258509 2.39789527]
 [1.38629436 1.60943791 1.94591015]]

If we use the shape function we would get (3, 3) as output, that is verifying that our matrix is a 3\times 3 matrix. We can slice the matrix and print for example the first column (Python organized matrix elements in a row-major order, see below) as

In [10]:
import numpy as np
A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
# print the first column, row-major order and elements start with 0
print(A[:,0])
[1.38629436 1.09861229 1.38629436]

We can continue this was by printing out other columns or rows. The example here prints out the second column

In [11]:
import numpy as np
A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
# print the first column, row-major order and elements start with 0
print(A[1,:])
[1.09861229 2.30258509 2.39789527]

Numpy contains many other functionalities that allow us to slice, subdivide etc etc arrays. We strongly recommend that you look up the Numpy website for more details. Useful functions when defining a matrix are the np.zeros function which declares a matrix of a given dimension and sets all elements to zero

In [12]:
import numpy as np
n = 10
# define a matrix of dimension 10 x 10 and set all elements to zero
A = np.zeros( (n, n) )
print(A)
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]

or initializing all elements to

In [13]:
import numpy as np
n = 10
# define a matrix of dimension 10 x 10 and set all elements to one
A = np.ones( (n, n) )
print(A)
[[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]]

or as unitarily distributed random numbers (see the material on random number generators in the statistics part)

In [14]:
import numpy as np
n = 10
# define a matrix of dimension 10 x 10 and set all elements to random numbers with x \in [0, 1]
A = np.random.rand(n, n)
print(A)
[[0.11167579 0.88778091 0.24908246 0.32566092 0.37585988 0.61893735
  0.58574143 0.60081665 0.81065392 0.00509527]
 [0.02840884 0.39600607 0.96810393 0.28213741 0.19237495 0.54219245
  0.85581869 0.17928538 0.43185254 0.37624303]
 [0.82045496 0.22828694 0.52773891 0.54526769 0.84708672 0.59118929
  0.18221254 0.94640767 0.25328924 0.03192893]
 [0.98328759 0.68996179 0.81168086 0.08086066 0.10659682 0.66599246
  0.78035464 0.57403561 0.96995249 0.78990036]
 [0.9909606  0.39920034 0.59813773 0.85982436 0.66665241 0.60522226
  0.08889302 0.74433499 0.85630009 0.2745333 ]
 [0.60826013 0.94413158 0.32305813 0.27011455 0.38636467 0.02568505
  0.0610602  0.92275042 0.09189927 0.67177934]
 [0.72097126 0.35819312 0.98060869 0.46573851 0.70482138 0.51749473
  0.17012048 0.53752634 0.66726905 0.08874264]
 [0.79974359 0.05023564 0.84150451 0.05491301 0.90643349 0.75505597
  0.7300372  0.57445493 0.39626502 0.22016672]
 [0.44463741 0.01448144 0.01167264 0.85595734 0.09989861 0.81007682
  0.30844205 0.68075712 0.9067362  0.96317459]
 [0.87327422 0.12086283 0.50504743 0.60715594 0.9440887  0.54041662
  0.7316348  0.42976761 0.63933182 0.22772039]]

As we will see throughout these lectures, there are several extremely useful functionalities in Numpy. As an example, consider the discussion of the covariance matrix. Suppose we have defined three vectors \boldsymbol{x}, \boldsymbol{y}, \boldsymbol{z} with n elements each. The covariance matrix is defined as


\boldsymbol{\Sigma} = \begin{bmatrix} \sigma_{xx} & \sigma_{xy} & \sigma_{xz} \\
                              \sigma_{yx} & \sigma_{yy} & \sigma_{yz} \\
                              \sigma_{zx} & \sigma_{zy} & \sigma_{zz} 
             \end{bmatrix},

where for example


\sigma_{xy} =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}).

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 3\times n matrix \boldsymbol{W}


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

which in turn is converted into into the 3\times 3 covariance matrix \boldsymbol{\Sigma} 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.

In [15]:
# 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))
z = x**3+np.random.normal(size=n)
print(np.mean(z))
W = np.vstack((x, y, z))
Sigma = np.cov(W)
print(Sigma)
Eigvals, Eigvecs = np.linalg.eig(Sigma)
print(Eigvals)
-0.05279147850537411
3.9698377974429513
0.22403397554517984
[[ 1.03173163  3.03859372  3.15084741]
 [ 3.03859372  9.96514849  9.33589475]
 [ 3.15084741  9.33589475 15.3141149 ]]
[23.20313883  0.08502083  3.02283536]
In [16]:
%matplotlib inline

import numpy as np
import matplotlib.pyplot as plt
from scipy import sparse
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()
[[1. 0. 0. 0.]
 [0. 1. 0. 0.]
 [0. 0. 1. 0.]
 [0. 0. 0. 1.]]
  (0, 0)	1.0
  (1, 1)	1.0
  (2, 2)	1.0
  (3, 3)	1.0

Meet the Pandas

Figure 1:

Another useful Python package is pandas, which is an open source library providing high-performance, easy-to-use data structures and data analysis tools for Python. pandas stands for panel data, a term borrowed from econometrics and is an efficient library for data analysis with an emphasis on tabular data. pandas has two major classes, the DataFrame class with two-dimensional data objects and tabular data organized in columns and the class Series with a focus on one-dimensional data objects. Both classes allow you to index data easily as we will see in the examples below. pandas allows you also to perform mathematical operations on the data, spanning from simple reshapings of vectors and matrices to statistical operations.

The following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, place of birth and date of birth, and displays the data in an easy to read way. We will see repeated use of pandas, in particular in connection with classification of data.

In [17]:
import pandas as pd
from IPython.display import display
data = {'First Name': ["Frodo", "Bilbo", "Aragorn II", "Samwise"],
        'Last Name': ["Baggins", "Baggins","Elessar","Gamgee"],
        'Place of birth': ["Shire", "Shire", "Eriador", "Shire"],
        'Date of Birth T.A.': [2968, 2890, 2931, 2980]
        }
data_pandas = pd.DataFrame(data)
display(data_pandas)
First Name Last Name Place of birth Date of Birth T.A.
0 Frodo Baggins Shire 2968
1 Bilbo Baggins Shire 2890
2 Aragorn II Elessar Eriador 2931
3 Samwise Gamgee Shire 2980

In the above we have imported pandas with the shorthand pd, the latter has become the standard way we import pandas. We make then a list of various variables and reorganize the aboves lists into a DataFrame and then print out a neat table with specific column labels as Name, place of birth and date of birth. Displaying these results, we see that the indices are given by the default numbers from zero to three. pandas is extremely flexible and we can easily change the above indices by defining a new type of indexing as

In [18]:
data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])
display(data_pandas)
First Name Last Name Place of birth Date of Birth T.A.
Frodo Frodo Baggins Shire 2968
Bilbo Bilbo Baggins Shire 2890
Aragorn Aragorn II Elessar Eriador 2931
Sam Samwise Gamgee Shire 2980

Thereafter we display the content of the row which begins with the index Aragorn

In [19]:
display(data_pandas.loc['Aragorn'])
First Name            Aragorn II
Last Name                Elessar
Place of birth           Eriador
Date of Birth T.A.          2931
Name: Aragorn, dtype: object

We can easily append data to this, for example

In [20]:
new_hobbit = {'First Name': ["Peregrin"],
              'Last Name': ["Took"],
              'Place of birth': ["Shire"],
              'Date of Birth T.A.': [2990]
              }
data_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin']))
display(data_pandas)
/var/folders/td/3yk470mj5p931p9dtkk0y6jw0000gn/T/ipykernel_16293/1326197715.py:6: FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.
  data_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin']))
First Name Last Name Place of birth Date of Birth T.A.
Frodo Frodo Baggins Shire 2968
Bilbo Bilbo Baggins Shire 2890
Aragorn Aragorn II Elessar Eriador 2931
Sam Samwise Gamgee Shire 2980
Pippin Peregrin Took Shire 2990

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.

In [21]:
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)
0 1 2 3 4
0 -1.749765 0.342680 1.153036 -0.252436 0.981321
1 0.514219 0.221180 -1.070043 -0.189496 0.255001
2 -0.458027 0.435163 -0.583595 0.816847 0.672721
3 -0.104411 -0.531280 1.029733 -0.438136 -1.118318
4 1.618982 1.541605 -0.251879 -0.842436 0.184519
5 0.937082 0.731000 1.361556 -0.326238 0.055676
6 0.222400 -1.443217 -0.756352 0.816454 0.750445
7 -0.455947 1.189622 -1.690617 -1.356399 -1.232435
8 -0.544439 -0.668172 0.007315 -0.612939 1.299748
9 -1.733096 -0.983310 0.357508 -1.613579 1.470714
0   -0.175300
1    0.083527
2   -0.044334
3   -0.399836
4    0.331939
dtype: float64
0    1.069584
1    0.965548
2    1.018232
3    0.793167
4    0.918992
dtype: float64
0 1 2 3 4
0 3.061679 0.117430 1.329492 0.063724 0.962990
1 0.264421 0.048920 1.144993 0.035909 0.065026
2 0.209789 0.189367 0.340583 0.667239 0.452553
3 0.010902 0.282259 1.060349 0.191963 1.250636
4 2.621102 2.376547 0.063443 0.709698 0.034047
5 0.878123 0.534362 1.853835 0.106431 0.003100
6 0.049462 2.082875 0.572069 0.666597 0.563167
7 0.207888 1.415201 2.858185 1.839818 1.518895
8 0.296414 0.446453 0.000054 0.375694 1.689345
9 3.003620 0.966899 0.127812 2.603636 2.162999

Thereafter we can select specific columns only and plot final results

In [22]:
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()
First Second Third Fourth Fifth
0 -1.749765 0.342680 1.153036 -0.252436 0.981321
1 0.514219 0.221180 -1.070043 -0.189496 0.255001
2 -0.458027 0.435163 -0.583595 0.816847 0.672721
3 -0.104411 -0.531280 1.029733 -0.438136 -1.118318
4 1.618982 1.541605 -0.251879 -0.842436 0.184519
5 0.937082 0.731000 1.361556 -0.326238 0.055676
6 0.222400 -1.443217 -0.756352 0.816454 0.750445
7 -0.455947 1.189622 -1.690617 -1.356399 -1.232435
8 -0.544439 -0.668172 0.007315 -0.612939 1.299748
9 -1.733096 -0.983310 0.357508 -1.613579 1.470714
0.08352721390288316
<class 'pandas.core.frame.DataFrame'>
Int64Index: 10 entries, 0 to 9
Data columns (total 5 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   First   10 non-null     float64
 1   Second  10 non-null     float64
 2   Third   10 non-null     float64
 3   Fourth  10 non-null     float64
 4   Fifth   10 non-null     float64
dtypes: float64(5)
memory usage: 480.0 bytes
None
           First     Second      Third     Fourth      Fifth
count  10.000000  10.000000  10.000000  10.000000  10.000000
mean   -0.175300   0.083527  -0.044334  -0.399836   0.331939
std     1.069584   0.965548   1.018232   0.793167   0.918992
min    -1.749765  -1.443217  -1.690617  -1.613579  -1.232435
25%    -0.522836  -0.633949  -0.713163  -0.785061   0.087887
50%    -0.280179   0.281930  -0.122282  -0.382187   0.463861
75%     0.441264   0.657041   0.861676  -0.205231   0.923602
max     1.618982   1.541605   1.361556   0.816847   1.470714

We can produce a 4\times 4 matrix

In [23]:
b = np.arange(16).reshape((4,4))
print(b)
df1 = pd.DataFrame(b)
print(df1)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]
    0   1   2   3
0   0   1   2   3
1   4   5   6   7
2   8   9  10  11
3  12  13  14  15

and many other operations.

The Series class is another important class included in pandas. You can view it as a specialization of DataFrame but where we have just a single column of data. It shares many of the same features as DataFrame. As with DataFrame, most operations are vectorized, achieving thereby a high performance when dealing with computations of arrays, in particular labeled arrays. As we will see below it leads also to a very concice code close to the mathematical operations we may be interested in. For multidimensional arrays, we recommend strongly xarray. xarray has much of the same flexibility as pandas, but allows for the extension to higher dimensions than two. We will see examples later of the usage of both pandas and xarray.

Simple linear regression model using scikit-learn

We start with perhaps our simplest possible example, using Scikit-Learn to perform linear regression analysis on a data set produced by us.

What follows is a simple Python code where we have defined a function y in terms of the variable x. Both are defined as vectors with 100 entries. The numbers in the vector \boldsymbol{x} are given by random numbers generated with a uniform distribution with entries x_i \in [0,1] (more about probability distribution functions later). These values are then used to define a function y(x) (tabulated again as a vector) with a linear dependence on x plus a random noise added via the normal distribution.

The Numpy functions are imported used the import numpy as np statement and the random number generator for the uniform distribution is called using the function np.random.rand(), where we specificy that we want 100 random variables. Using Numpy we define automatically an array with the specified number of elements, 100 in our case. With the Numpy function randn() we can compute random numbers with the normal distribution (mean value \mu equal to zero and variance \sigma^2 set to one) and produce the values of y assuming a linear dependence as function of x


y = 2x+N(0,1),

where N(0,1) represents random numbers generated by the normal distribution. From Scikit-Learn we import then the LinearRegression functionality and make a prediction $\tilde{y} = \alpha + \beta x$ using the function fit(x,y). We call the set of data (\boldsymbol{x},\boldsymbol{y}) for our training data. The Python package scikit-learn has also a functionality which extracts the above fitting parameters \alpha and \beta (see below). Later we will distinguish between training data and test data.

For plotting we use the Python package matplotlib which produces publication quality figures. Feel free to explore the extensive gallery of examples. In this example we plot our original values of x and y as well as the prediction ypredict (\tilde{y}), which attempts at fitting our data with a straight line.

The Python code follows here.

In [24]:
# Importing various packages
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

x = np.random.rand(100,1)
y = 2*x+np.random.randn(100,1)
linreg = LinearRegression()
linreg.fit(x,y)
xnew = np.array([[0],[1]])
ypredict = linreg.predict(xnew)

plt.plot(xnew, ypredict, "r-")
plt.plot(x, y ,'ro')
plt.axis([0,1.0,0, 5.0])
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')
plt.title(r'Simple Linear Regression')
plt.show()

This example serves several aims. It allows us to demonstrate several aspects of data analysis and later machine learning algorithms. The immediate visualization shows that our linear fit is not impressive. It goes through the data points, but there are many outliers which are not reproduced by our linear regression. We could now play around with this small program and change for example the factor in front of x and the normal distribution. Try to change the function y to


y = 10x+0.01 \times N(0,1),

where x is defined as before. Does the fit look better? Indeed, by reducing the role of the noise given by the normal distribution we see immediately that our linear prediction seemingly reproduces better the training set. However, this testing 'by the eye' is obviouly not satisfactory in the long run. Here we have only defined the training data and our model, and have not discussed a more rigorous approach to the cost function.

We need more rigorous criteria in defining whether we have succeeded or not in modeling our training data. You will be surprised to see that many scientists seldomly venture beyond this 'by the eye' approach. A standard approach for the cost function is the so-called \chi^2 function (a variant of the mean-squared error (MSE))


\chi^2 = \frac{1}{n}
\sum_{i=0}^{n-1}\frac{(y_i-\tilde{y}_i)^2}{\sigma_i^2},

where \sigma_i^2 is the variance (to be defined later) of the entry y_i. We may not know the explicit value of \sigma_i^2, it serves however the aim of scaling the equations and make the cost function dimensionless.

Minimizing the cost function is a central aspect of our discussions to come. Finding its minima as function of the model parameters (\alpha and \beta in our case) will be a recurring theme in these series of lectures. Essentially all machine learning algorithms we will discuss center around the minimization of the chosen cost function. This depends in turn on our specific model for describing the data, a typical situation in supervised learning. Automatizing the search for the minima of the cost function is a central ingredient in all algorithms. Typical methods which are employed are various variants of gradient methods. These will be discussed in more detail later. Again, you'll be surprised to hear that many practitioners minimize the above function ''by the eye', popularly dubbed as 'chi by the eye'. That is, change a parameter and see (visually and numerically) that the \chi^2 function becomes smaller.

There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define the relative error (why would we prefer the MSE instead of the relative error?) as


\epsilon_{\mathrm{relative}}= \frac{\vert \boldsymbol{y} -\boldsymbol{\tilde{y}}\vert}{\vert \boldsymbol{y}\vert}.
Warning:
Output truncated. This notebook contains too many cells to display efficiently.