2402 lines
100 KiB
Plaintext
2402 lines
100 KiB
Plaintext
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"<!-- dom:TITLE: Data Analysis and Machine Learning -->\n",
|
|
"# Data Analysis and Machine Learning\n",
|
|
"<!-- dom:AUTHOR: Morten Hjorth-Jensen at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University -->\n",
|
|
"<!-- Author: --> \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: **Dec 22, 2019**\n",
|
|
"\n",
|
|
"Copyright 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"# Introduction\n",
|
|
"\n",
|
|
"\n",
|
|
"During the last two decades there has been a swift and amazing\n",
|
|
"development of Machine Learning techniques and algorithms that impact\n",
|
|
"many areas in not only Science and Technology but also the Humanities,\n",
|
|
"Social Sciences, Medicine, Law, indeed, almost all possible\n",
|
|
"disciplines. The applications are incredibly many, from self-driving\n",
|
|
"cars to solving high-dimensional differential equations or complicated\n",
|
|
"quantum mechanical many-body problems. Machine Learning is perceived\n",
|
|
"by many as one of the main disruptive techniques nowadays. \n",
|
|
"\n",
|
|
"Statistics, Data science and Machine Learning form important\n",
|
|
"fields of research in modern science. They describe how to learn and\n",
|
|
"make predictions from data, as well as allowing us to extract\n",
|
|
"important correlations about physical process and the underlying laws\n",
|
|
"of motion in large data sets. The latter, big data sets, appear\n",
|
|
"frequently in essentially all disciplines, from the traditional\n",
|
|
"Science, Technology, Mathematics and Engineering fields to Life\n",
|
|
"Science, Law, education research, the Humanities and the Social\n",
|
|
"Sciences.\n",
|
|
"\n",
|
|
"It has become more\n",
|
|
"and more common to see research projects on big data in for example\n",
|
|
"the Social Sciences where extracting patterns from complicated survey\n",
|
|
"data is one of many research directions. Having a solid grasp of data\n",
|
|
"analysis and machine learning is thus becoming central to scientific\n",
|
|
"computing in many fields, and competences and skills within the fields\n",
|
|
"of machine learning and scientific computing are nowadays strongly\n",
|
|
"requested by many potential employers. The latter cannot be\n",
|
|
"overstated, familiarity with machine learning has almost become a\n",
|
|
"prerequisite for many of the most exciting employment opportunities,\n",
|
|
"whether they are in bioinformatics, life science, physics or finance,\n",
|
|
"in the private or the public sector. This author has had several\n",
|
|
"students or met students who have been hired recently based on their\n",
|
|
"skills and competences in scientific computing and data science, often\n",
|
|
"with marginal knowledge of machine learning.\n",
|
|
"\n",
|
|
"Machine learning is a subfield of computer science, and is closely\n",
|
|
"related to computational statistics. It evolved from the study of\n",
|
|
"pattern recognition in artificial intelligence (AI) research, and has\n",
|
|
"made contributions to AI tasks like computer vision, natural language\n",
|
|
"processing and speech recognition. Many of the methods we will study are also \n",
|
|
"strongly rooted in basic mathematics and physics research. \n",
|
|
"\n",
|
|
"Ideally, machine learning represents the science of giving computers\n",
|
|
"the ability to learn without being explicitly programmed. The idea is\n",
|
|
"that there exist generic algorithms which can be used to find patterns\n",
|
|
"in a broad class of data sets without having to write code\n",
|
|
"specifically for each problem. The algorithm will build its own logic\n",
|
|
"based on the data. You should however always keep in mind that\n",
|
|
"machines and algorithms are to a large extent developed by humans. The\n",
|
|
"insights and knowledge we have about a specific system, play a central\n",
|
|
"role when we develop a specific machine learning algorithm. \n",
|
|
"\n",
|
|
"Machine learning is an extremely rich field, in spite of its young\n",
|
|
"age. The increases we have seen during the last three decades in\n",
|
|
"computational capabilities have been followed by developments of\n",
|
|
"methods and techniques for analyzing and handling large date sets,\n",
|
|
"relying heavily on statistics, computer science and mathematics. The\n",
|
|
"field is rather new and developing rapidly. Popular software packages\n",
|
|
"written in Python for machine learning like\n",
|
|
"[Scikit-learn](http://scikit-learn.org/stable/),\n",
|
|
"[Tensorflow](https://www.tensorflow.org/),\n",
|
|
"[PyTorch](http://pytorch.org/) and [Keras](https://keras.io/), all\n",
|
|
"freely available at their respective GitHub sites, encompass\n",
|
|
"communities of developers in the thousands or more. And the number of\n",
|
|
"code developers and contributors keeps increasing. Not all the\n",
|
|
"algorithms and methods can be given a rigorous mathematical\n",
|
|
"justification, opening up thereby large rooms for experimenting and\n",
|
|
"trial and error and thereby exciting new developments. However, a\n",
|
|
"solid command of linear algebra, multivariate theory, probability\n",
|
|
"theory, statistical data analysis, understanding errors and Monte\n",
|
|
"Carlo methods are central elements in a proper understanding of many\n",
|
|
"of algorithms and methods we will discuss.\n",
|
|
"\n",
|
|
"\n",
|
|
"## Learning outcomes\n",
|
|
"\n",
|
|
"These sets of lectures aim at giving you an overview of central aspects of\n",
|
|
"statistical data analysis as well as some of the central algorithms\n",
|
|
"used in machine learning. We will introduce a variety of central\n",
|
|
"algorithms and methods essential for studies of data analysis and\n",
|
|
"machine learning. \n",
|
|
"\n",
|
|
"Hands-on projects and experimenting with data and algorithms plays a central role in\n",
|
|
"these lectures, and our hope is, through the various\n",
|
|
"projects and exercises, to expose you to fundamental\n",
|
|
"research problems in these fields, with the aim to reproduce state of\n",
|
|
"the art scientific results. You will learn to develop and\n",
|
|
"structure codes for studying these systems, get acquainted with\n",
|
|
"computing facilities and learn to handle large scientific projects. A\n",
|
|
"good scientific and ethical conduct is emphasized throughout the\n",
|
|
"course. More specifically, you will\n",
|
|
"\n",
|
|
"1. Learn about basic data analysis, Bayesian statistics, Monte Carlo methods, data optimization and machine learning;\n",
|
|
"\n",
|
|
"2. Be capable of extending the acquired knowledge to other systems and cases;\n",
|
|
"\n",
|
|
"3. Have an understanding of central algorithms used in data analysis and machine learning;\n",
|
|
"\n",
|
|
"4. Gain knowledge of central aspects of Monte Carlo methods, Markov chains, Gibbs samplers and their possible applications, from numerical integration to simulation of stock markets;\n",
|
|
"\n",
|
|
"5. Understand methods for regression and classification;\n",
|
|
"\n",
|
|
"6. Learn about neural network, genetic algorithms and Boltzmann machines;\n",
|
|
"\n",
|
|
"7. 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++, in addition to a basic knowledge of linear algebra (typically taught during the first one or two years of undergraduate studies).\n",
|
|
"\n",
|
|
"There are several topics we will cover here, spanning from \n",
|
|
"statistical data analysis and its basic concepts such as expectation\n",
|
|
"values, variance, covariance, correlation functions and errors, via\n",
|
|
"well-known probability distribution functions like the uniform\n",
|
|
"distribution, the binomial distribution, the Poisson distribution and\n",
|
|
"simple and multivariate normal distributions to central elements of\n",
|
|
"Bayesian statistics and modeling. We will also remind the reader about\n",
|
|
"central elements from linear algebra and standard methods based on\n",
|
|
"linear algebra used to optimize (minimize) functions (the family of gradient descent methods)\n",
|
|
"and the Singular-value decomposition and\n",
|
|
"least square methods for parameterizing data.\n",
|
|
"\n",
|
|
"We will also cover Monte Carlo methods, Markov chains, well-known\n",
|
|
"algorithms for sampling stochastic events like the Metropolis-Hastings\n",
|
|
"and Gibbs sampling methods. An important aspect of all our\n",
|
|
"calculations is a proper estimation of errors. Here we will also\n",
|
|
"discuss famous resampling techniques like the blocking, the bootstrapping\n",
|
|
"and the jackknife methods and the infamous bias-variance tradeoff. \n",
|
|
"\n",
|
|
"The second part of the material covers several algorithms used in\n",
|
|
"machine learning.\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"## Types of Machine Learning\n",
|
|
"\n",
|
|
"\n",
|
|
"The approaches to machine learning are many, but are often split into\n",
|
|
"two main categories. In *supervised learning* we know the answer to a\n",
|
|
"problem, and let the computer deduce the logic behind it. On the other\n",
|
|
"hand, *unsupervised learning* is a method for finding patterns and\n",
|
|
"relationship in data sets without any prior knowledge of the system.\n",
|
|
"Some authours also operate with a third category, namely\n",
|
|
"*reinforcement learning*. This is a paradigm of learning inspired by\n",
|
|
"behavioral psychology, where learning is achieved by trial-and-error,\n",
|
|
"solely from rewards and punishment.\n",
|
|
"\n",
|
|
"Another way to categorize machine learning tasks is to consider the\n",
|
|
"desired output of a system. Some of the most common tasks are:\n",
|
|
"\n",
|
|
" * 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.\n",
|
|
"\n",
|
|
" * 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.\n",
|
|
"\n",
|
|
" * Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning.\n",
|
|
"\n",
|
|
"The methods we cover have three main topics in common, irrespective of\n",
|
|
"whether we deal with supervised or unsupervised learning. The first\n",
|
|
"ingredient is normally our data set (which can be subdivided into\n",
|
|
"training and test data), the second item is a model which is normally\n",
|
|
"a function of some parameters. The model reflects our knowledge of\n",
|
|
"the system (or lack thereof). As an example, if we know that our data\n",
|
|
"show a behavior similar to what would be predicted by a polynomial,\n",
|
|
"fitting our data to a polynomial of some degree would then determin\n",
|
|
"our model.\n",
|
|
"\n",
|
|
"The last ingredient is a so-called **cost**\n",
|
|
"function which allows us to present an estimate on how good our model\n",
|
|
"is in reproducing the data it is supposed to train. \n",
|
|
"\n",
|
|
"Here we will build our machine learning approach on elements of the\n",
|
|
"statistical foundation discussed above, with elements from data\n",
|
|
"analysis, stochastic processes etc. We will discuss the following\n",
|
|
"machine learning algorithms\n",
|
|
"\n",
|
|
"1. Linear regression and its variants\n",
|
|
"\n",
|
|
"2. Decision tree algorithms, from single trees to random forests\n",
|
|
"\n",
|
|
"3. Bayesian statistics and regression\n",
|
|
"\n",
|
|
"4. Support vector machines and finally various variants of\n",
|
|
"\n",
|
|
"5. Artifical neural networks and deep learning, including convolutional neural networks and Bayesian neural networks\n",
|
|
"\n",
|
|
"6. Networks for unsupervised learning using for example reduced Boltzmann machines.\n",
|
|
"\n",
|
|
"## Choice of programming language\n",
|
|
"\n",
|
|
"Python plays nowadays a central role in the development of machine\n",
|
|
"learning techniques and tools for data analysis. In particular, seen\n",
|
|
"the wealth of machine learning and data analysis libraries written in\n",
|
|
"Python, easy to use libraries with immediate visualization(and not the\n",
|
|
"least impressive galleries of existing examples), the popularity of the\n",
|
|
"Jupyter notebook framework with the possibility to run **R** codes or\n",
|
|
"compiled programs written in C++, and much more made our choice of\n",
|
|
"programming language for this series of lectures easy. However,\n",
|
|
"since the focus here is not only on using existing Python libraries such\n",
|
|
"as **Scikit-Learn** or **Tensorflow**, but also on developing your own\n",
|
|
"algorithms and codes, we will as far as possible present many of these\n",
|
|
"algorithms either as a Python codes or C++ or Fortran (or other languages) codes. \n",
|
|
"\n",
|
|
"The reason we also focus on compiled languages like C++ (or\n",
|
|
"Fortran), is that Python is still notoriously slow when we do not\n",
|
|
"utilize highly streamlined computational libraries like\n",
|
|
"[Lapack](http://www.netlib.org/lapack/) or other numerical libraries\n",
|
|
"written in compiled languages (many of these libraries are written in\n",
|
|
"Fortran). Although a project like [Numba](https://numba.pydata.org/)\n",
|
|
"holds great promise for speeding up the unrolling of lengthy loops, C++\n",
|
|
"and Fortran are presently still the performance winners. Numba gives\n",
|
|
"you potentially the power to speed up your applications with high\n",
|
|
"performance functions written directly in Python. In particular,\n",
|
|
"array-oriented and math-heavy Python code can achieve similar\n",
|
|
"performance to C, C++ and Fortran. However, even with these speed-ups,\n",
|
|
"for codes involving heavy Markov Chain Monte Carlo analyses and\n",
|
|
"optimizations of cost functions, C++/C or Fortran codes tend to\n",
|
|
"outperform Python codes. \n",
|
|
"\n",
|
|
"Presently thus, the community tends to let\n",
|
|
"code written in C++/C or Fortran do the heavy duty numerical\n",
|
|
"number crunching and leave the post-analysis of the data to the above\n",
|
|
"mentioned Python modules or software packages. However, with the developments taking place in for example the Python community, and seen\n",
|
|
"the changes during the last decade, the above situation may change swiftly in the not too distant future. \n",
|
|
"\n",
|
|
"Many of the examples we discuss in this series of lectures come with\n",
|
|
"existing data files or provide code examples which produce the data to\n",
|
|
"be analyzed. Most of the applications we will discuss deal with\n",
|
|
"small data sets (less than a terabyte of information) and can easily\n",
|
|
"be analyzed and tested on standard off the shelf laptops you find in general \n",
|
|
"stores.\n",
|
|
"\n",
|
|
"## Data handling, machine learning and ethical aspects\n",
|
|
"\n",
|
|
"In most of the cases we will study, we will either generate the data\n",
|
|
"to analyze ourselves (both for supervised learning and unsupervised\n",
|
|
"learning) or we will recur again and again to data present in say\n",
|
|
"**Scikit-Learn** or **Tensorflow**. Many of the examples we end up\n",
|
|
"dealing with are from a privacy and data protection point of view,\n",
|
|
"rather inoccuous and boring results of numerical\n",
|
|
"calculations. However, this does not hinder us from developing a sound\n",
|
|
"ethical attitude to the data we use, how we analyze the data and how\n",
|
|
"we handle the data.\n",
|
|
"\n",
|
|
"The most immediate and simplest possible ethical aspects deal with our\n",
|
|
"approach to the scientific process. Nowadays, with version control\n",
|
|
"software like [Git](https://git-scm.com/) and various online\n",
|
|
"repositories like [Github](https://github.com/),\n",
|
|
"[Gitlab](https://about.gitlab.com/) etc, we can easily make our codes\n",
|
|
"and data sets we have used, freely and easily accessible to a wider\n",
|
|
"community. This helps us almost automagically in making our science\n",
|
|
"reproducible. The large open-source development communities involved\n",
|
|
"in say [Scikit-Learn](http://scikit-learn.org/stable/),\n",
|
|
"[Tensorflow](https://www.tensorflow.org/),\n",
|
|
"[PyTorch](http://pytorch.org/) and [Keras](https://keras.io/), are\n",
|
|
"all excellent examples of this. The codes can be tested and improved\n",
|
|
"upon continuosly, helping thereby our scientific community at large in\n",
|
|
"developing data analysis and machine learning tools. It is much\n",
|
|
"easier today to gain traction and acceptance for making your science\n",
|
|
"reproducible. From a societal stand, this is an important element\n",
|
|
"since many of the developers are employees of large public institutions like\n",
|
|
"universities and research labs. Our fellow taxpayers do deserve to get\n",
|
|
"something back for their bucks.\n",
|
|
"\n",
|
|
"However, this more mechanical aspect of the ethics of science (in\n",
|
|
"particular the reproducibility of scientific results) is something\n",
|
|
"which is obvious and everybody should do so as part of the dialectics of\n",
|
|
"science. The fact that many scientists are not willing to share their codes or \n",
|
|
"data is detrimental to the scientific discourse.\n",
|
|
"\n",
|
|
"Before we proceed, we should add a disclaimer. Even though\n",
|
|
"we may dream of computers developing some kind of higher learning\n",
|
|
"capabilities, at the end (even if the artificial intelligence\n",
|
|
"community keeps touting our ears full of fancy futuristic avenues), it is we, yes you reading these lines,\n",
|
|
"who end up constructing and instructing, via various algorithms, the\n",
|
|
"machine learning approaches. Self-driving cars for example, rely on sofisticated\n",
|
|
"programs which take into account all possible situations a car can\n",
|
|
"encounter. In addition, extensive usage of training data from GPS\n",
|
|
"information, maps etc, are typically fed into the software for\n",
|
|
"self-driving cars. Adding to this various sensors and cameras that\n",
|
|
"feed information to the programs, there are zillions of ethical issues\n",
|
|
"which arise from this.\n",
|
|
"\n",
|
|
"For self-driving cars, where basically many of the standard machine\n",
|
|
"learning algorithms discussed here enter into the codes, at a certain\n",
|
|
"stage we have to make choices. Yes, we , the lads and lasses who wrote\n",
|
|
"a program for a specific brand of a self-driving car. As an example,\n",
|
|
"all carmakers have as their utmost priority the security of the\n",
|
|
"driver and the accompanying passengers. A famous European carmaker, which is\n",
|
|
"one of the leaders in the market of self-driving cars, had **if**\n",
|
|
"statements of the following type: suppose there are two obstacles in\n",
|
|
"front of you and you cannot avoid to collide with one of them. One of\n",
|
|
"the obstacles is a monstertruck while the other one is a kindergarten\n",
|
|
"class trying to cross the road. The self-driving car algo would then\n",
|
|
"opt for the hitting the small folks instead of the monstertruck, since\n",
|
|
"the likelihood of surving a collision with our future citizens, is\n",
|
|
"much higher.\n",
|
|
"\n",
|
|
"This leads to serious ethical aspects. Why should we opt for such an\n",
|
|
"option? Who decides and who is entitled to make such choices? Keep in\n",
|
|
"mind that many of the algorithms you will encounter in this series of\n",
|
|
"lectures or hear about later, are indeed based on simple programming\n",
|
|
"instructions. And you are very likely to be one of the people who may\n",
|
|
"end up writing such a code. Thus, developing a sound ethical attitude\n",
|
|
"to what we do, an approach well beyond the simple mechanistic one of\n",
|
|
"making our science available and reproducible, is much needed. The\n",
|
|
"example of the self-driving cars is just one of infinitely many cases\n",
|
|
"where we have to make choices. When you analyze data on economic\n",
|
|
"inequalities, who guarantees that you are not weighting some data in a\n",
|
|
"particular way, perhaps because you dearly want a specific conclusion\n",
|
|
"which may support your political views? Or what about the recent\n",
|
|
"claims that a famous IT company like Apple has a sexist bias on the\n",
|
|
"their recently [launched credit card](https://qz.com/1748321/the-role-of-goldman-sachs-algorithms-in-the-apple-credit-card-scandal/)?\n",
|
|
"\n",
|
|
"We do not have the answers here, nor will we venture into a deeper\n",
|
|
"discussions of these aspects, but we want you think over these topics\n",
|
|
"in a more overarching way. A statistical data analysis with its dry\n",
|
|
"numbers and graphs meant to guide the eye, does not necessarily\n",
|
|
"reflect the truth, whatever that is. As a scientist, and after a\n",
|
|
"university education, you are supposedly a better citizen, with an\n",
|
|
"improved critical view and understanding of the scientific method, and\n",
|
|
"perhaps some deeper understanding of the ethics of science at\n",
|
|
"large. Use these insights. Be a critical citizen. You owe it to our\n",
|
|
"society.\n",
|
|
"\n",
|
|
"\n",
|
|
"# Machine Learning Overview with Selectec Examples\n",
|
|
"\n",
|
|
"\n",
|
|
"## Introduction\n",
|
|
"\n",
|
|
"Our emphasis throughout this series of lectures \n",
|
|
"is on understanding the mathematical aspects of\n",
|
|
"different algorithms used in the fields of data analysis and machine learning. \n",
|
|
"\n",
|
|
"However, where possible we will emphasize the\n",
|
|
"importance of using available software. We start thus with a hands-on\n",
|
|
"and top-down approach to machine learning. The aim is thus to start with\n",
|
|
"relevant data or data we have produced \n",
|
|
"and use these to introduce statistical data analysis\n",
|
|
"concepts and machine learning algorithms before we delve into the\n",
|
|
"algorithms themselves. The examples we will use in the beginning, start with simple\n",
|
|
"polynomials with random noise added. We will use the Python\n",
|
|
"software package [Scikit-Learn](http://scikit-learn.org/stable/) and\n",
|
|
"introduce various machine learning algorithms to make fits of\n",
|
|
"the data and predictions. We move thereafter to more interesting\n",
|
|
"cases such as data from say experiments (below we will look at experimental nuclear binding energies as an example).\n",
|
|
"These are examples where we can easily set up the data and\n",
|
|
"then use machine learning algorithms included in for example\n",
|
|
"**Scikit-Learn**. \n",
|
|
"\n",
|
|
"These examples will serve us the purpose of getting\n",
|
|
"started. Furthermore, they allow us to catch more than two birds with\n",
|
|
"a stone. They will allow us to bring in some programming specific\n",
|
|
"topics and tools as well as showing the power of various Python \n",
|
|
"libraries for machine learning and statistical data analysis. \n",
|
|
"\n",
|
|
"Here, we will mainly focus on two\n",
|
|
"specific Python packages for Machine Learning, Scikit-Learn and\n",
|
|
"Tensorflow (see below for links etc). Moreover, the examples we\n",
|
|
"introduce will serve as inputs to many of our discussions later, as\n",
|
|
"well as allowing you to set up models and produce your own data and\n",
|
|
"get started with programming.\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"## What is Machine Learning?\n",
|
|
"\n",
|
|
"Statistics, data science and machine learning form important fields of\n",
|
|
"research in modern science. They describe how to learn and make\n",
|
|
"predictions from data, as well as allowing us to extract important\n",
|
|
"correlations about physical process and the underlying laws of motion\n",
|
|
"in large data sets. The latter, big data sets, appear frequently in\n",
|
|
"essentially all disciplines, from the traditional Science, Technology,\n",
|
|
"Mathematics and Engineering fields to Life Science, Law, education\n",
|
|
"research, the Humanities and the Social Sciences. \n",
|
|
"\n",
|
|
"It has become more\n",
|
|
"and more common to see research projects on big data in for example\n",
|
|
"the Social Sciences where extracting patterns from complicated survey\n",
|
|
"data is one of many research directions. Having a solid grasp of data\n",
|
|
"analysis and machine learning is thus becoming central to scientific\n",
|
|
"computing in many fields, and competences and skills within the fields\n",
|
|
"of machine learning and scientific computing are nowadays strongly\n",
|
|
"requested by many potential employers. The latter cannot be\n",
|
|
"overstated, familiarity with machine learning has almost become a\n",
|
|
"prerequisite for many of the most exciting employment opportunities,\n",
|
|
"whether they are in bioinformatics, life science, physics or finance,\n",
|
|
"in the private or the public sector. This author has had several\n",
|
|
"students or met students who have been hired recently based on their\n",
|
|
"skills and competences in scientific computing and data science, often\n",
|
|
"with marginal knowledge of machine learning.\n",
|
|
"\n",
|
|
"Machine learning is a subfield of computer science, and is closely\n",
|
|
"related to computational statistics. It evolved from the study of\n",
|
|
"pattern recognition in artificial intelligence (AI) research, and has\n",
|
|
"made contributions to AI tasks like computer vision, natural language\n",
|
|
"processing and speech recognition. Many of the methods we will study are also \n",
|
|
"strongly rooted in basic mathematics and physics research. \n",
|
|
"\n",
|
|
"Ideally, machine learning represents the science of giving computers\n",
|
|
"the ability to learn without being explicitly programmed. The idea is\n",
|
|
"that there exist generic algorithms which can be used to find patterns\n",
|
|
"in a broad class of data sets without having to write code\n",
|
|
"specifically for each problem. The algorithm will build its own logic\n",
|
|
"based on the data. You should however always keep in mind that\n",
|
|
"machines and algorithms are to a large extent developed by humans. The\n",
|
|
"insights and knowledge we have about a specific system, play a central\n",
|
|
"role when we develop a specific machine learning algorithm. \n",
|
|
"\n",
|
|
"Machine learning is an extremely rich field, in spite of its young\n",
|
|
"age. The increases we have seen during the last three decades in\n",
|
|
"computational capabilities have been followed by developments of\n",
|
|
"methods and techniques for analyzing and handling large date sets,\n",
|
|
"relying heavily on statistics, computer science and mathematics. The\n",
|
|
"field is rather new and developing rapidly. Popular software packages\n",
|
|
"written in Python for machine learning like\n",
|
|
"[Scikit-learn](http://scikit-learn.org/stable/),\n",
|
|
"[Tensorflow](https://www.tensorflow.org/),\n",
|
|
"[PyTorch](http://pytorch.org/) and [Keras](https://keras.io/), all\n",
|
|
"freely available at their respective GitHub sites, encompass\n",
|
|
"communities of developers in the thousands or more. And the number of\n",
|
|
"code developers and contributors keeps increasing. Not all the\n",
|
|
"algorithms and methods can be given a rigorous mathematical\n",
|
|
"justification, opening up thereby large rooms for experimenting and\n",
|
|
"trial and error and thereby exciting new developments. However, a\n",
|
|
"solid command of linear algebra, multivariate theory, probability\n",
|
|
"theory, statistical data analysis, understanding errors and Monte\n",
|
|
"Carlo methods are central elements in a proper understanding of many\n",
|
|
"of algorithms and methods we will discuss.\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"## Types of Machine Learning\n",
|
|
"\n",
|
|
"\n",
|
|
"The approaches to machine learning are many, but are often split into\n",
|
|
"two main categories. In *supervised learning* we know the answer to a\n",
|
|
"problem, and let the computer deduce the logic behind it. On the other\n",
|
|
"hand, *unsupervised learning* is a method for finding patterns and\n",
|
|
"relationship in data sets without any prior knowledge of the system.\n",
|
|
"Some authours also operate with a third category, namely\n",
|
|
"*reinforcement learning*. This is a paradigm of learning inspired by\n",
|
|
"behavioral psychology, where learning is achieved by trial-and-error,\n",
|
|
"solely from rewards and punishment.\n",
|
|
"\n",
|
|
"Another way to categorize machine learning tasks is to consider the\n",
|
|
"desired output of a system. Some of the most common tasks are:\n",
|
|
"\n",
|
|
" * 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.\n",
|
|
"\n",
|
|
" * 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.\n",
|
|
"\n",
|
|
" * Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning.\n",
|
|
"\n",
|
|
"The methods we cover have three main topics in common, irrespective of\n",
|
|
"whether we deal with supervised or unsupervised learning. The first\n",
|
|
"ingredient is normally our data set (which can be subdivided into\n",
|
|
"training and test data), the second item is a model which is normally a\n",
|
|
"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. \n",
|
|
"\n",
|
|
"The last ingredient is a so-called **cost**\n",
|
|
"function which allows us to present an estimate on how good our model\n",
|
|
"is in reproducing the data it is supposed to train. \n",
|
|
"At the heart of basically all ML algorithms there are so-called minimization algorithms, often we end up with various variants of **gradient** methods.\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"## Software and needed installations\n",
|
|
"\n",
|
|
"We will make extensive use of Python as programming language and its\n",
|
|
"myriad of available libraries. You will find\n",
|
|
"Jupyter notebooks invaluable in your work. You can run **R**\n",
|
|
"codes in the Jupyter/IPython notebooks, with the immediate benefit of\n",
|
|
"visualizing your data. You can also use compiled languages like C++,\n",
|
|
"Rust, Julia, Fortran etc if you prefer. The focus in these lectures will be\n",
|
|
"on Python.\n",
|
|
"\n",
|
|
"\n",
|
|
"If you have Python installed (we strongly recommend Python3) and you feel\n",
|
|
"pretty familiar with installing different packages, we recommend that\n",
|
|
"you install the following Python packages via **pip** as \n",
|
|
"\n",
|
|
"1. pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow \n",
|
|
"\n",
|
|
"For Python3, replace **pip** with **pip3**.\n",
|
|
"\n",
|
|
"For OSX users we recommend, after having installed Xcode, to\n",
|
|
"install **brew**. Brew allows for a seamless installation of additional\n",
|
|
"software via for example \n",
|
|
"\n",
|
|
"1. brew install python3\n",
|
|
"\n",
|
|
"For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,\n",
|
|
"you can use **pip** as well and simply install Python as \n",
|
|
"\n",
|
|
"1. sudo apt-get install python3 (or python for pyhton2.7)\n",
|
|
"\n",
|
|
"etc etc. \n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"## Python installers\n",
|
|
"\n",
|
|
"If you don't want to perform these operations separately and venture\n",
|
|
"into the hassle of exploring how to set up dependencies and paths, we\n",
|
|
"recommend two widely used distrubutions which set up all relevant\n",
|
|
"dependencies for Python, namely \n",
|
|
"\n",
|
|
"* [Anaconda](https://docs.anaconda.com/), \n",
|
|
"\n",
|
|
"which is an open source\n",
|
|
"distribution of the Python and R programming languages for large-scale\n",
|
|
"data processing, predictive analytics, and scientific computing, that\n",
|
|
"aims to simplify package management and deployment. Package versions\n",
|
|
"are managed by the package management system **conda**. \n",
|
|
"\n",
|
|
"* [Enthought canopy](https://www.enthought.com/product/canopy/) \n",
|
|
"\n",
|
|
"is a Python\n",
|
|
"distribution for scientific and analytic computing distribution and\n",
|
|
"analysis environment, available for free and under a commercial\n",
|
|
"license.\n",
|
|
"\n",
|
|
"Furthermore, [Google's Colab](https://colab.research.google.com/notebooks/welcome.ipynb) is a free Jupyter notebook environment that requires \n",
|
|
"no setup and runs entirely in the cloud. Try it out!\n",
|
|
"\n",
|
|
"## Useful Python libraries\n",
|
|
"Here we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there)\n",
|
|
"\n",
|
|
"* [NumPy](https://www.numpy.org/) 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\n",
|
|
"\n",
|
|
"* [The pandas](https://pandas.pydata.org/) library provides high-performance, easy-to-use data structures and data analysis tools \n",
|
|
"\n",
|
|
"* [Xarray](http://xarray.pydata.org/en/stable/) is a Python package that makes working with labelled multi-dimensional arrays simple, efficient, and fun!\n",
|
|
"\n",
|
|
"* [Scipy](https://www.scipy.org/) (pronounced “Sigh Pie”) is a Python-based ecosystem of open-source software for mathematics, science, and engineering. \n",
|
|
"\n",
|
|
"* [Matplotlib](https://matplotlib.org/) is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.\n",
|
|
"\n",
|
|
"* [Autograd](https://github.com/HIPS/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\n",
|
|
"\n",
|
|
"* [SymPy](https://www.sympy.org/en/index.html) is a Python library for symbolic mathematics. \n",
|
|
"\n",
|
|
"* [scikit-learn](https://scikit-learn.org/stable/) has simple and efficient tools for machine learning, data mining and data analysis\n",
|
|
"\n",
|
|
"* [TensorFlow](https://www.tensorflow.org/) is a Python library for fast numerical computing created and released by Google\n",
|
|
"\n",
|
|
"* [Keras](https://keras.io/) is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano\n",
|
|
"\n",
|
|
"* And many more such as [pytorch](https://pytorch.org/), [Theano](https://pypi.org/project/Theano/) etc \n",
|
|
"\n",
|
|
"## Installing R, C++, cython or Julia\n",
|
|
"\n",
|
|
"You will also find it convenient to utilize **R**. We will mainly\n",
|
|
"use Python during our lectures and in various projects and exercises.\n",
|
|
"Those of you\n",
|
|
"already familiar with **R** should feel free to continue using **R**, keeping\n",
|
|
"however an eye on the parallel Python set ups. Similarly, if you are a\n",
|
|
"Python afecionado, feel free to explore **R** as well. Jupyter/Ipython\n",
|
|
"notebook allows you to run **R** codes interactively in your\n",
|
|
"browser. The software library **R** is really tailored for statistical data analysis\n",
|
|
"and allows for an easy usage of the tools and algorithms we will discuss in these\n",
|
|
"lectures.\n",
|
|
"\n",
|
|
"To install **R** with Jupyter notebook \n",
|
|
"[follow the link here](https://mpacer.org/maths/r-kernel-for-ipython-notebook)\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"## Installing R, C++, cython, Numba etc\n",
|
|
"\n",
|
|
"\n",
|
|
"For the C++ aficionados, Jupyter/IPython notebook allows you also to\n",
|
|
"install C++ and run codes written in this language interactively in\n",
|
|
"the browser. Since we will emphasize writing many of the algorithms\n",
|
|
"yourself, you can thus opt for either Python or C++ (or Fortran or other compiled languages) as programming\n",
|
|
"languages.\n",
|
|
"\n",
|
|
"To add more entropy, **cython** can also be used when running your\n",
|
|
"notebooks. It means that Python with the jupyter notebook\n",
|
|
"setup allows you to integrate widely popular softwares and tools for\n",
|
|
"scientific computing. Similarly, the \n",
|
|
"[Numba Python package](https://numba.pydata.org/) delivers increased performance\n",
|
|
"capabilities with minimal rewrites of your codes. With its\n",
|
|
"versatility, including symbolic operations, Python offers a unique\n",
|
|
"computational environment. Your jupyter notebook can easily be\n",
|
|
"converted into a nicely rendered **PDF** file or a Latex file for\n",
|
|
"further processing. For example, convert to latex as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
" pycod jupyter nbconvert filename.ipynb --to latex \n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"And to add more versatility, the Python package [SymPy](http://www.sympy.org/en/index.html) is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python. \n",
|
|
"\n",
|
|
"Finally, if you wish to use the light mark-up language \n",
|
|
"[doconce](https://github.com/hplgit/doconce) you can convert a standard ascii text file into various HTML \n",
|
|
"formats, ipython notebooks, latex files, pdf files etc with minimal edits. These lectures were generated using **doconce**.\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"## Numpy examples and Important Matrix and vector handling packages\n",
|
|
"\n",
|
|
"There are several central software libraries for linear algebra and eigenvalue problems. Several of the more\n",
|
|
"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\n",
|
|
"software package LAPACK, which follows two other popular packages\n",
|
|
"developed in the 1970s, namely EISPACK and LINPACK. We describe them shortly here.\n",
|
|
"\n",
|
|
" * LINPACK: package for linear equations and least square problems.\n",
|
|
"\n",
|
|
" * 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.\n",
|
|
"\n",
|
|
" * 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>.\n",
|
|
"\n",
|
|
"## Basic Matrix Features\n",
|
|
"\n",
|
|
"**Matrix properties reminder.**"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\mathbf{A} =\n",
|
|
" \\begin{bmatrix} a_{11} & a_{12} & a_{13} & a_{14} \\\\\n",
|
|
" a_{21} & a_{22} & a_{23} & a_{24} \\\\\n",
|
|
" a_{31} & a_{32} & a_{33} & a_{34} \\\\\n",
|
|
" a_{41} & a_{42} & a_{43} & a_{44}\n",
|
|
" \\end{bmatrix}\\qquad\n",
|
|
"\\mathbf{I} =\n",
|
|
" \\begin{bmatrix} 1 & 0 & 0 & 0 \\\\\n",
|
|
" 0 & 1 & 0 & 0 \\\\\n",
|
|
" 0 & 0 & 1 & 0 \\\\\n",
|
|
" 0 & 0 & 0 & 1\n",
|
|
" \\end{bmatrix}\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The inverse of a matrix is defined by"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\mathbf{A}^{-1} \\cdot \\mathbf{A} = I\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"<table border=\"1\">\n",
|
|
"<thead>\n",
|
|
"<tr><th align=\"center\"> Relations </th> <th align=\"center\"> Name </th> <th align=\"center\"> matrix elements </th> </tr>\n",
|
|
"</thead>\n",
|
|
"<tbody>\n",
|
|
"<tr><td align=\"center\"> $A = A^{T}$ </td> <td align=\"center\"> symmetric </td> <td align=\"center\"> $a_{ij} = a_{ji}$ </td> </tr>\n",
|
|
"<tr><td align=\"center\"> $A = \\left (A^{T} \\right )^{-1}$ </td> <td align=\"center\"> real orthogonal </td> <td align=\"center\"> $\\sum_k a_{ik} a_{jk} = \\sum_k a_{ki} a_{kj} = \\delta_{ij}$ </td> </tr>\n",
|
|
"<tr><td align=\"center\"> $A = A^{ * }$ </td> <td align=\"center\"> real matrix </td> <td align=\"center\"> $a_{ij} = a_{ij}^{ * }$ </td> </tr>\n",
|
|
"<tr><td align=\"center\"> $A = A^{\\dagger}$ </td> <td align=\"center\"> hermitian </td> <td align=\"center\"> $a_{ij} = a_{ji}^{ * }$ </td> </tr>\n",
|
|
"<tr><td align=\"center\"> $A = \\left (A^{\\dagger} \\right )^{-1}$ </td> <td align=\"center\"> unitary </td> <td align=\"center\"> $\\sum_k a_{ik} a_{jk}^{ * } = \\sum_k a_{ki}^{ * } a_{kj} = \\delta_{ij}$ </td> </tr>\n",
|
|
"</tbody>\n",
|
|
"</table>\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"### Some famous Matrices\n",
|
|
"\n",
|
|
" * Diagonal if $a_{ij}=0$ for $i\\ne j$\n",
|
|
"\n",
|
|
" * Upper triangular if $a_{ij}=0$ for $i > j$\n",
|
|
"\n",
|
|
" * Lower triangular if $a_{ij}=0$ for $i < j$\n",
|
|
"\n",
|
|
" * Upper Hessenberg if $a_{ij}=0$ for $i > j+1$\n",
|
|
"\n",
|
|
" * Lower Hessenberg if $a_{ij}=0$ for $i < j+1$\n",
|
|
"\n",
|
|
" * Tridiagonal if $a_{ij}=0$ for $|i -j| > 1$\n",
|
|
"\n",
|
|
" * Lower banded with bandwidth $p$: $a_{ij}=0$ for $i > j+p$\n",
|
|
"\n",
|
|
" * Upper banded with bandwidth $p$: $a_{ij}=0$ for $i < j+p$\n",
|
|
"\n",
|
|
" * Banded, block upper triangular, block lower triangular....\n",
|
|
"\n",
|
|
"### More Basic Matrix Features\n",
|
|
"\n",
|
|
"**Some Equivalent Statements.**\n",
|
|
"\n",
|
|
"For an $N\\times N$ matrix $\\mathbf{A}$ the following properties are all equivalent\n",
|
|
"\n",
|
|
" * If the inverse of $\\mathbf{A}$ exists, $\\mathbf{A}$ is nonsingular.\n",
|
|
"\n",
|
|
" * The equation $\\mathbf{Ax}=0$ implies $\\mathbf{x}=0$.\n",
|
|
"\n",
|
|
" * The rows of $\\mathbf{A}$ form a basis of $R^N$.\n",
|
|
"\n",
|
|
" * The columns of $\\mathbf{A}$ form a basis of $R^N$.\n",
|
|
"\n",
|
|
" * $\\mathbf{A}$ is a product of elementary matrices.\n",
|
|
"\n",
|
|
" * $0$ is not eigenvalue of $\\mathbf{A}$.\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"## Numpy and arrays\n",
|
|
"[Numpy](http://www.numpy.org/) provides an easy way to handle arrays in Python. The standard way to import this library is as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 1,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"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,"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 2,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"n = 10\n",
|
|
"x = np.random.normal(size=n)\n",
|
|
"print(x)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"We defined a vector $x$ with $n=10$ elements with its values given by the Normal distribution $N(0,1)$.\n",
|
|
"Another alternative is to declare a vector as follows"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 3,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"x = np.array([1, 2, 3])\n",
|
|
"print(x)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"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++\n",
|
|
"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"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 4,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"x = np.log(np.array([4, 7, 8]))\n",
|
|
"print(x)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"In the last example we used Numpy's unary function $np.log$. This function is\n",
|
|
"highly tuned to compute array elements since the code is vectorized\n",
|
|
"and does not require looping. We normaly recommend that you use the\n",
|
|
"Numpy intrinsic functions instead of the corresponding **log** function\n",
|
|
"from Python's **math** module. The looping is done explicitely by the\n",
|
|
"**np.log** function. The alternative, and slower way to compute the\n",
|
|
"logarithms of a vector would be to write"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 5,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"from math import log\n",
|
|
"x = np.array([4, 7, 8])\n",
|
|
"for i in range(0, len(x)):\n",
|
|
" x[i] = log(x[i])\n",
|
|
"print(x)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"We note that our code is much longer already and we need to import the **log** function from the **math** module. \n",
|
|
"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"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 6,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"x = np.log(np.array([4, 7, 8], dtype = np.float64))\n",
|
|
"print(x)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"or simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 7,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"x = np.log(np.array([4.0, 7.0, 8.0])\n",
|
|
"print(x)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"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"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 8,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"x = np.log(np.array([4.0, 7.0, 8.0])\n",
|
|
"print(x.itemsize)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Matrices in Python\n",
|
|
"\n",
|
|
"Having defined vectors, we are now ready to try out matrices. We can\n",
|
|
"define a $3 \\times 3 $ real matrix $\\hat{A}$ as (recall that we user\n",
|
|
"lowercase letters for vectors and uppercase letters for matrices)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 9,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n",
|
|
"print(A)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"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"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 10,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n",
|
|
"# print the first column, row-major order and elements start with 0\n",
|
|
"print(A[:,0])"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"We can continue this was by printing out other columns or rows. The example here prints out the second column"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 11,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n",
|
|
"# print the first column, row-major order and elements start with 0\n",
|
|
"print(A[1,:])"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"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](http://www.numpy.org/). 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"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 12,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"n = 10\n",
|
|
"# define a matrix of dimension 10 x 10 and set all elements to zero\n",
|
|
"A = np.zeros( (n, n) )\n",
|
|
"print(A)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"or initializing all elements to"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 13,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"n = 10\n",
|
|
"# define a matrix of dimension 10 x 10 and set all elements to one\n",
|
|
"A = np.ones( (n, n) )\n",
|
|
"print(A)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"or as unitarily distributed random numbers (see the material on random number generators in the statistics part)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 14,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"n = 10\n",
|
|
"# define a matrix of dimension 10 x 10 and set all elements to random numbers with x \\in [0, 1]\n",
|
|
"A = np.random.rand(n, n)\n",
|
|
"print(A)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"As we will see throughout these lectures, there are several extremely useful functionalities in Numpy.\n",
|
|
"As an example, consider the discussion of the covariance matrix. Suppose we have defined three vectors\n",
|
|
"$\\hat{x}, \\hat{y}, \\hat{z}$ with $n$ elements each. The covariance matrix is defined as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\hat{\\Sigma} = \\begin{bmatrix} \\sigma_{xx} & \\sigma_{xy} & \\sigma_{xz} \\\\\n",
|
|
" \\sigma_{yx} & \\sigma_{yy} & \\sigma_{yz} \\\\\n",
|
|
" \\sigma_{zx} & \\sigma_{zy} & \\sigma_{zz} \n",
|
|
" \\end{bmatrix},\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"where for example"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\sigma_{xy} =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"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. \n",
|
|
"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 $\\hat{W}$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\hat{W} = \\begin{bmatrix} x_0 & y_0 & z_0 \\\\\n",
|
|
" x_1 & y_1 & z_1 \\\\\n",
|
|
" x_2 & y_2 & z_2 \\\\\n",
|
|
" \\dots & \\dots & \\dots \\\\\n",
|
|
" x_{n-2} & y_{n-2} & z_{n-2} \\\\\n",
|
|
" x_{n-1} & y_{n-1} & z_{n-1}\n",
|
|
" \\end{bmatrix},\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"which in turn is converted into into the $3\\times 3$ covariance matrix\n",
|
|
"$\\hat{\\Sigma}$ via the Numpy function **np.cov()**. We note that we can also calculate\n",
|
|
"the mean value of each set of samples $\\hat{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": 15,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Importing various packages\n",
|
|
"import numpy as np\n",
|
|
"\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",
|
|
"z = x**3+np.random.normal(size=n)\n",
|
|
"print(np.mean(z))\n",
|
|
"W = np.vstack((x, y, z))\n",
|
|
"Sigma = np.cov(W)\n",
|
|
"print(Sigma)\n",
|
|
"Eigvals, Eigvecs = np.linalg.eig(Sigma)\n",
|
|
"print(Eigvals)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 16,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"%matplotlib inline\n",
|
|
"\n",
|
|
"import numpy as np\n",
|
|
"import matplotlib.pyplot as plt\n",
|
|
"from scipy import sparse\n",
|
|
"eye = np.eye(4)\n",
|
|
"print(eye)\n",
|
|
"sparse_mtx = sparse.csr_matrix(eye)\n",
|
|
"print(sparse_mtx)\n",
|
|
"x = np.linspace(-10,10,100)\n",
|
|
"y = np.sin(x)\n",
|
|
"plt.plot(x,y,marker='x')\n",
|
|
"plt.show()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Meet the Pandas\n",
|
|
"\n",
|
|
"\n",
|
|
"<!-- dom:FIGURE: [fig/pandas.jpg, width=600 frac=0.8] -->\n",
|
|
"<!-- begin figure -->\n",
|
|
"\n",
|
|
"<p></p>\n",
|
|
"<img src=\"fig/pandas.jpg\" width=600>\n",
|
|
"\n",
|
|
"<!-- end figure -->\n",
|
|
"\n",
|
|
"\n",
|
|
"Another useful Python package is\n",
|
|
"[pandas](https://pandas.pydata.org/), which is an open source library\n",
|
|
"providing high-performance, easy-to-use data structures and data\n",
|
|
"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.\n",
|
|
"**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. \n",
|
|
"**pandas** allows you also to perform mathematical operations on the data, spanning from simple reshapings of vectors and matrices to statistical operations. \n",
|
|
"\n",
|
|
"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."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 17,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import pandas as pd\n",
|
|
"from IPython.display import display\n",
|
|
"data = {'First Name': [\"Frodo\", \"Bilbo\", \"Aragorn II\", \"Samwise\"],\n",
|
|
" 'Last Name': [\"Baggins\", \"Baggins\",\"Elessar\",\"Gamgee\"],\n",
|
|
" 'Place of birth': [\"Shire\", \"Shire\", \"Eriador\", \"Shire\"],\n",
|
|
" 'Date of Birth T.A.': [2968, 2890, 2931, 2980]\n",
|
|
" }\n",
|
|
"data_pandas = pd.DataFrame(data)\n",
|
|
"display(data_pandas)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"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\n",
|
|
"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*.\n",
|
|
"Displaying these results, we see that the indices are given by the default numbers from zero to three.\n",
|
|
"**pandas** is extremely flexible and we can easily change the above indices by defining a new type of indexing as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 18,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])\n",
|
|
"display(data_pandas)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Thereafter we display the content of the row which begins with the index **Aragorn**"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 19,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"display(data_pandas.loc['Aragorn'])"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"We can easily append data to this, for example"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 20,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"new_hobbit = {'First Name': [\"Peregrin\"],\n",
|
|
" 'Last Name': [\"Took\"],\n",
|
|
" 'Place of birth': [\"Shire\"],\n",
|
|
" 'Date of Birth T.A.': [2990]\n",
|
|
" }\n",
|
|
"data_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin']))\n",
|
|
"display(data_pandas)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"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": 21,
|
|
"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": 22,
|
|
"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": 23,
|
|
"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. \n",
|
|
"\n",
|
|
"The **Series** class is another important class included in\n",
|
|
"**pandas**. You can view it as a specialization of **DataFrame** but where\n",
|
|
"we have just a single column of data. It shares many of the same features as _DataFrame. As with **DataFrame**,\n",
|
|
"most operations are vectorized, achieving thereby a high performance when dealing with computations of arrays, in particular labeled arrays.\n",
|
|
"As we will see below it leads also to a very concice code close to the mathematical operations we may be interested in.\n",
|
|
"For multidimensional arrays, we recommend strongly [xarray](http://xarray.pydata.org/en/stable/). **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**. \n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"## Reading Data and fitting\n",
|
|
"\n",
|
|
"In order to study various Machine Learning algorithms, we need to\n",
|
|
"access data. Acccessing data is an essential step in all machine\n",
|
|
"learning algorithms. In particular, setting up the so-called **design\n",
|
|
"matrix** (to be defined below) is often the first element we need in\n",
|
|
"order to perform our calculations. To set up the design matrix means\n",
|
|
"reading (and later, when the calculations are done, writing) data\n",
|
|
"in various formats, The formats span from reading files from disk,\n",
|
|
"loading data from databases and interacting with online sources\n",
|
|
"like web application programming interfaces (APIs).\n",
|
|
"\n",
|
|
"In handling various input formats, as discussed above, we will mainly stay with **pandas**,\n",
|
|
"a Python package which allows us, in a seamless and painless way, to\n",
|
|
"deal with a multitude of formats, from standard **csv** (comma separated\n",
|
|
"values) files, via **excel**, **html** to **hdf5** formats. With **pandas**\n",
|
|
"and the **DataFrame** and **Series** functionalities we are able to convert text data\n",
|
|
"into the calculational formats we need for a specific algorithm. And our code is going to be \n",
|
|
"pretty close the basic mathematical expressions.\n",
|
|
"\n",
|
|
"Our first data set is going to be a classic from nuclear physics, namely all\n",
|
|
"available data on binding energies. Don't be intimidated if you are not familiar with nuclear physics. It serves simply as an example here of a data set. \n",
|
|
"\n",
|
|
"We will show some of the\n",
|
|
"strengths of packages like **Scikit-Learn** in fitting nuclear binding energies to\n",
|
|
"specific functions using linear regression first. Then, as a teaser, we will show you how \n",
|
|
"you can easily implement other algorithms like decision trees and random forests and neural networks.\n",
|
|
"\n",
|
|
"But before we really start with nuclear physics data, let's just look at some simpler polynomial fitting cases, such as,\n",
|
|
"(don't be offended) fitting straight lines!\n",
|
|
"\n",
|
|
"\n",
|
|
"### Simple linear regression model using **scikit-learn**\n",
|
|
"\n",
|
|
"We start with perhaps our simplest possible example, using **Scikit-Learn** to perform linear regression analysis on a data set produced by us. \n",
|
|
"\n",
|
|
"What follows is a simple Python code where we have defined a function\n",
|
|
"$y$ in terms of the variable $x$. Both are defined as vectors with $100$ entries. \n",
|
|
"The numbers in the vector $\\hat{x}$ are given\n",
|
|
"by random numbers generated with a uniform distribution with entries\n",
|
|
"$x_i \\in [0,1]$ (more about probability distribution functions\n",
|
|
"later). These values are then used to define a function $y(x)$\n",
|
|
"(tabulated again as a vector) with a linear dependence on $x$ plus a\n",
|
|
"random noise added via the normal distribution.\n",
|
|
"\n",
|
|
"\n",
|
|
"The Numpy functions are imported used the **import numpy as np**\n",
|
|
"statement and the random number generator for the uniform distribution\n",
|
|
"is called using the function **np.random.rand()**, where we specificy\n",
|
|
"that we want $100$ random variables. Using Numpy we define\n",
|
|
"automatically an array with the specified number of elements, $100$ in\n",
|
|
"our case. With the Numpy function **randn()** we can compute random\n",
|
|
"numbers with the normal distribution (mean value $\\mu$ equal to zero and\n",
|
|
"variance $\\sigma^2$ set to one) and produce the values of $y$ assuming a linear\n",
|
|
"dependence as function of $x$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"y = 2x+N(0,1),\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"where $N(0,1)$ represents random numbers generated by the normal\n",
|
|
"distribution. From **Scikit-Learn** we import then the\n",
|
|
"**LinearRegression** functionality and make a prediction $\\tilde{y} =\n",
|
|
"\\alpha + \\beta x$ using the function **fit(x,y)**. We call the set of\n",
|
|
"data $(\\hat{x},\\hat{y})$ for our training data. The Python package\n",
|
|
"**scikit-learn** has also a functionality which extracts the above\n",
|
|
"fitting parameters $\\alpha$ and $\\beta$ (see below). Later we will\n",
|
|
"distinguish between training data and test data.\n",
|
|
"\n",
|
|
"For plotting we use the Python package\n",
|
|
"[matplotlib](https://matplotlib.org/) which produces publication\n",
|
|
"quality figures. Feel free to explore the extensive\n",
|
|
"[gallery](https://matplotlib.org/gallery/index.html) of examples. In\n",
|
|
"this example we plot our original values of $x$ and $y$ as well as the\n",
|
|
"prediction **ypredict** ($\\tilde{y}$), which attempts at fitting our\n",
|
|
"data with a straight line.\n",
|
|
"\n",
|
|
"The Python code follows here."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 24,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Importing various packages\n",
|
|
"import numpy as np\n",
|
|
"import matplotlib.pyplot as plt\n",
|
|
"from sklearn.linear_model import LinearRegression\n",
|
|
"\n",
|
|
"x = np.random.rand(100,1)\n",
|
|
"y = 2*x+np.random.randn(100,1)\n",
|
|
"linreg = LinearRegression()\n",
|
|
"linreg.fit(x,y)\n",
|
|
"xnew = np.array([[0],[1]])\n",
|
|
"ypredict = linreg.predict(xnew)\n",
|
|
"\n",
|
|
"plt.plot(xnew, ypredict, \"r-\")\n",
|
|
"plt.plot(x, y ,'ro')\n",
|
|
"plt.axis([0,1.0,0, 5.0])\n",
|
|
"plt.xlabel(r'$x$')\n",
|
|
"plt.ylabel(r'$y$')\n",
|
|
"plt.title(r'Simple Linear Regression')\n",
|
|
"plt.show()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"This example serves several aims. It allows us to demonstrate several\n",
|
|
"aspects of data analysis and later machine learning algorithms. The\n",
|
|
"immediate visualization shows that our linear fit is not\n",
|
|
"impressive. It goes through the data points, but there are many\n",
|
|
"outliers which are not reproduced by our linear regression. We could\n",
|
|
"now play around with this small program and change for example the\n",
|
|
"factor in front of $x$ and the normal distribution. Try to change the\n",
|
|
"function $y$ to"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"y = 10x+0.01 \\times N(0,1),\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"where $x$ is defined as before. Does the fit look better? Indeed, by\n",
|
|
"reducing the role of the noise given by the normal distribution we see immediately that\n",
|
|
"our linear prediction seemingly reproduces better the training\n",
|
|
"set. However, this testing 'by the eye' is obviouly not satisfactory in the\n",
|
|
"long run. Here we have only defined the training data and our model, and \n",
|
|
"have not discussed a more rigorous approach to the **cost** function.\n",
|
|
"\n",
|
|
"We need more rigorous criteria in defining whether we have succeeded or\n",
|
|
"not in modeling our training data. You will be surprised to see that\n",
|
|
"many scientists seldomly venture beyond this 'by the eye' approach. A\n",
|
|
"standard approach for the *cost* function is the so-called $\\chi^2$\n",
|
|
"function (a variant of the mean-squared error (MSE))"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\chi^2 = \\frac{1}{n}\n",
|
|
"\\sum_{i=0}^{n-1}\\frac{(y_i-\\tilde{y}_i)^2}{\\sigma_i^2},\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"where $\\sigma_i^2$ is the variance (to be defined later) of the entry\n",
|
|
"$y_i$. We may not know the explicit value of $\\sigma_i^2$, it serves\n",
|
|
"however the aim of scaling the equations and make the cost function\n",
|
|
"dimensionless. \n",
|
|
"\n",
|
|
"Minimizing the cost function is a central aspect of\n",
|
|
"our discussions to come. Finding its minima as function of the model\n",
|
|
"parameters ($\\alpha$ and $\\beta$ in our case) will be a recurring\n",
|
|
"theme in these series of lectures. Essentially all machine learning\n",
|
|
"algorithms we will discuss center around the minimization of the\n",
|
|
"chosen cost function. This depends in turn on our specific\n",
|
|
"model for describing the data, a typical situation in supervised\n",
|
|
"learning. Automatizing the search for the minima of the cost function is a\n",
|
|
"central ingredient in all algorithms. Typical methods which are\n",
|
|
"employed are various variants of **gradient** methods. These will be\n",
|
|
"discussed in more detail later. Again, you'll be surprised to hear that\n",
|
|
"many practitioners minimize the above function ''by the eye', popularly dubbed as \n",
|
|
"'chi by the eye'. That is, change a parameter and see (visually and numerically) that \n",
|
|
"the $\\chi^2$ function becomes smaller. \n",
|
|
"\n",
|
|
"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 \n",
|
|
"the relative error (why would we prefer the MSE instead of the relative error?) as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\epsilon_{\\mathrm{relative}}= \\frac{\\vert \\hat{y} -\\hat{\\tilde{y}}\\vert}{\\vert \\hat{y}\\vert}.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The squared cost function results in an arithmetic mean-unbiased\n",
|
|
"estimator, and the absolute-value cost function results in a\n",
|
|
"median-unbiased estimator (in the one-dimensional case, and a\n",
|
|
"geometric median-unbiased estimator for the multi-dimensional\n",
|
|
"case). The squared cost function has the disadvantage that it has the tendency\n",
|
|
"to be dominated by outliers.\n",
|
|
"\n",
|
|
"We can modify easily the above Python code and plot the relative error instead"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 25,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"import matplotlib.pyplot as plt\n",
|
|
"from sklearn.linear_model import LinearRegression\n",
|
|
"\n",
|
|
"x = np.random.rand(100,1)\n",
|
|
"y = 5*x+0.01*np.random.randn(100,1)\n",
|
|
"linreg = LinearRegression()\n",
|
|
"linreg.fit(x,y)\n",
|
|
"ypredict = linreg.predict(x)\n",
|
|
"\n",
|
|
"plt.plot(x, np.abs(ypredict-y)/abs(y), \"ro\")\n",
|
|
"plt.axis([0,1.0,0.0, 0.5])\n",
|
|
"plt.xlabel(r'$x$')\n",
|
|
"plt.ylabel(r'$\\epsilon_{\\mathrm{relative}}$')\n",
|
|
"plt.title(r'Relative error')\n",
|
|
"plt.show()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Depending on the parameter in front of the normal distribution, we may\n",
|
|
"have a small or larger relative error. Try to play around with\n",
|
|
"different training data sets and study (graphically) the value of the\n",
|
|
"relative error.\n",
|
|
"\n",
|
|
"As mentioned above, **Scikit-Learn** has an impressive functionality.\n",
|
|
"We can for example extract the values of $\\alpha$ and $\\beta$ and\n",
|
|
"their error estimates, or the variance and standard deviation and many\n",
|
|
"other properties from the statistical data analysis. \n",
|
|
"\n",
|
|
"Here we show an\n",
|
|
"example of the functionality of **Scikit-Learn**."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 26,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np \n",
|
|
"import matplotlib.pyplot as plt \n",
|
|
"from sklearn.linear_model import LinearRegression \n",
|
|
"from sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error\n",
|
|
"\n",
|
|
"x = np.random.rand(100,1)\n",
|
|
"y = 2.0+ 5*x+0.5*np.random.randn(100,1)\n",
|
|
"linreg = LinearRegression()\n",
|
|
"linreg.fit(x,y)\n",
|
|
"ypredict = linreg.predict(x)\n",
|
|
"print('The intercept alpha: \\n', linreg.intercept_)\n",
|
|
"print('Coefficient beta : \\n', linreg.coef_)\n",
|
|
"# The mean squared error \n",
|
|
"print(\"Mean squared error: %.2f\" % mean_squared_error(y, ypredict))\n",
|
|
"# Explained variance score: 1 is perfect prediction \n",
|
|
"print('Variance score: %.2f' % r2_score(y, ypredict))\n",
|
|
"# Mean squared log error \n",
|
|
"print('Mean squared log error: %.2f' % mean_squared_log_error(y, ypredict) )\n",
|
|
"# Mean absolute error \n",
|
|
"print('Mean absolute error: %.2f' % mean_absolute_error(y, ypredict))\n",
|
|
"plt.plot(x, ypredict, \"r-\")\n",
|
|
"plt.plot(x, y ,'ro')\n",
|
|
"plt.axis([0.0,1.0,1.5, 7.0])\n",
|
|
"plt.xlabel(r'$x$')\n",
|
|
"plt.ylabel(r'$y$')\n",
|
|
"plt.title(r'Linear Regression fit ')\n",
|
|
"plt.show()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The function **coef** gives us the parameter $\\beta$ of our fit while **intercept** yields \n",
|
|
"$\\alpha$. Depending on the constant in front of the normal distribution, we get values near or far from $alpha =2$ and $\\beta =5$. Try to play around with different parameters in front of the normal distribution. The function **meansquarederror** gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"MSE(\\hat{y},\\hat{\\tilde{y}}) = \\frac{1}{n}\n",
|
|
"\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The smaller the value, the better the fit. Ideally we would like to\n",
|
|
"have an MSE equal zero. The attentive reader has probably recognized\n",
|
|
"this function as being similar to the $\\chi^2$ function defined above.\n",
|
|
"\n",
|
|
"The **r2score** function computes $R^2$, the coefficient of\n",
|
|
"determination. It provides a measure of how well future samples are\n",
|
|
"likely to be predicted by the model. Best possible score is 1.0 and it\n",
|
|
"can be negative (because the model can be arbitrarily worse). A\n",
|
|
"constant model that always predicts the expected value of $\\hat{y}$,\n",
|
|
"disregarding the input features, would get a $R^2$ score of $0.0$.\n",
|
|
"\n",
|
|
"If $\\tilde{\\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"R^2(\\hat{y}, \\tilde{\\hat{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"where we have defined the mean value of $\\hat{y}$ as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Another quantity taht we will meet again in our discussions of regression analysis is \n",
|
|
" the mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the $l1$-norm loss. In our discussion above we presented the relative error.\n",
|
|
"The MAE is defined as follows"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\text{MAE}(\\hat{y}, \\hat{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n-1} \\left| y_i - \\tilde{y}_i \\right|.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"We present the \n",
|
|
"squared logarithmic (quadratic) error"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\text{MSLE}(\\hat{y}, \\hat{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n - 1} (\\log_e (1 + y_i) - \\log_e (1 + \\tilde{y}_i) )^2,\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"where $\\log_e (x)$ stands for the natural logarithm of $x$. This error\n",
|
|
"estimate is best to use when targets having exponential growth, such\n",
|
|
"as population counts, average sales of a commodity over a span of\n",
|
|
"years etc. \n",
|
|
"\n",
|
|
"\n",
|
|
"Finally, another cost function is the Huber cost function used in robust regression.\n",
|
|
"It is less sensitive to outliers in data than the squared error cost function.\n",
|
|
"A variant for classification is also sometimes used, a quantity we will meet later."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"L_{\\delta }(a)={\\begin{cases}{\\frac {1}{2}}{a^{2}}&{\\text{for }}|a|\\leq \\delta ,\\\\\\delta (|a|-{\\frac {1}{2}}\\delta ),&{\\text{otherwise.}}\\end{cases}}}L_{\\delta }(a)={\\begin{cases}{\\frac {1}{2}}{a^{2}}&{\\text{for }}|a|\\leq \\delta ,\\\\\\delta (|a|-{\\frac {1}{2}}\\delta ),&{\\text{otherwise.}}\\end{cases}}\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"We will discuss in more\n",
|
|
"detail these and other functions in the various lectures. We conclude this part with another example. Instead of \n",
|
|
"a linear $x$-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 27,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import matplotlib.pyplot as plt\n",
|
|
"import numpy as np\n",
|
|
"import random\n",
|
|
"from sklearn.linear_model import Ridge\n",
|
|
"from sklearn.preprocessing import PolynomialFeatures\n",
|
|
"from sklearn.pipeline import make_pipeline\n",
|
|
"from sklearn.linear_model import LinearRegression\n",
|
|
"\n",
|
|
"x=np.linspace(0.02,0.98,200)\n",
|
|
"noise = np.asarray(random.sample((range(200)),200))\n",
|
|
"y=x**3*noise\n",
|
|
"yn=x**3*100\n",
|
|
"poly3 = PolynomialFeatures(degree=3)\n",
|
|
"X = poly3.fit_transform(x[:,np.newaxis])\n",
|
|
"clf3 = LinearRegression()\n",
|
|
"clf3.fit(X,y)\n",
|
|
"\n",
|
|
"Xplot=poly3.fit_transform(x[:,np.newaxis])\n",
|
|
"poly3_plot=plt.plot(x, clf3.predict(Xplot), label='Cubic Fit')\n",
|
|
"plt.plot(x,yn, color='red', label=\"True Cubic\")\n",
|
|
"plt.scatter(x, y, label='Data', color='orange', s=15)\n",
|
|
"plt.legend()\n",
|
|
"plt.show()\n",
|
|
"\n",
|
|
"def error(a):\n",
|
|
" for i in y:\n",
|
|
" err=(y-yn)/yn\n",
|
|
" return abs(np.sum(err))/len(err)\n",
|
|
"\n",
|
|
"print (error(y))"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### To our real data: nuclear binding energies. Brief reminder on masses and binding energies\n",
|
|
"\n",
|
|
"Let us now dive into nuclear physics and remind ourselves briefly about some basic features about binding\n",
|
|
"energies. A basic quantity which can be measured for the ground\n",
|
|
"states of nuclei is the atomic mass $M(N, Z)$ of the neutral atom with\n",
|
|
"atomic mass number $A$ and charge $Z$. The number of neutrons is $N$. There are indeed several sophisticated experiments worldwide which allow us to measure this quantity to high precision (parts per million even). \n",
|
|
"\n",
|
|
"Atomic masses are usually tabulated in terms of the mass excess defined by"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\Delta M(N, Z) = M(N, Z) - uA,\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"where $u$ is the Atomic Mass Unit"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"u = M(^{12}\\mathrm{C})/12 = 931.4940954(57) \\hspace{0.1cm} \\mathrm{MeV}/c^2.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The nucleon masses are"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"m_p = 1.00727646693(9)u,\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"and"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"m_n = 939.56536(8)\\hspace{0.1cm} \\mathrm{MeV}/c^2 = 1.0086649156(6)u.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"In the [2016 mass evaluation of by W.J.Huang, G.Audi, M.Wang, F.G.Kondev, S.Naimi and X.Xu](http://nuclearmasses.org/resources_folder/Wang_2017_Chinese_Phys_C_41_030003.pdf)\n",
|
|
"there are data on masses and decays of 3437 nuclei.\n",
|
|
"\n",
|
|
"The nuclear binding energy is defined as the energy required to break\n",
|
|
"up a given nucleus into its constituent parts of $N$ neutrons and $Z$\n",
|
|
"protons. In terms of the atomic masses $M(N, Z)$ the binding energy is\n",
|
|
"defined by"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"BE(N, Z) = ZM_H c^2 + Nm_n c^2 - M(N, Z)c^2 ,\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"where $M_H$ is the mass of the hydrogen atom and $m_n$ is the mass of the neutron.\n",
|
|
"In terms of the mass excess the binding energy is given by"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"BE(N, Z) = Z\\Delta_H c^2 + N\\Delta_n c^2 -\\Delta(N, Z)c^2 ,\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"where $\\Delta_H c^2 = 7.2890$ MeV and $\\Delta_n c^2 = 8.0713$ MeV.\n",
|
|
"\n",
|
|
"\n",
|
|
"A popular and physically intuitive model which can be used to parametrize \n",
|
|
"the experimental binding energies as function of $A$, is the so-called \n",
|
|
"**liquid drop model**. The ansatz is based on the following expression"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"BE(N,Z) = a_1A-a_2A^{2/3}-a_3\\frac{Z^2}{A^{1/3}}-a_4\\frac{(N-Z)^2}{A},\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"where $A$ stands for the number of nucleons and the $a_i$s are parameters which are determined by a fit \n",
|
|
"to the experimental data. \n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"To arrive at the above expression we have assumed that we can make the following assumptions:\n",
|
|
"\n",
|
|
" * There is a volume term $a_1A$ proportional with the number of nucleons (the energy is also an extensive quantity). When an assembly of nucleons of the same size is packed together into the smallest volume, each interior nucleon has a certain number of other nucleons in contact with it. This contribution is proportional to the volume.\n",
|
|
"\n",
|
|
" * There is a surface energy term $a_2A^{2/3}$. The assumption here is that a nucleon at the surface of a nucleus interacts with fewer other nucleons than one in the interior of the nucleus and hence its binding energy is less. This surface energy term takes that into account and is therefore negative and is proportional to the surface area.\n",
|
|
"\n",
|
|
" * There is a Coulomb energy term $a_3\\frac{Z^2}{A^{1/3}}$. The electric repulsion between each pair of protons in a nucleus yields less binding. \n",
|
|
"\n",
|
|
" * There is an asymmetry term $a_4\\frac{(N-Z)^2}{A}$. This term is associated with the Pauli exclusion principle and reflects the fact that the proton-neutron interaction is more attractive on the average than the neutron-neutron and proton-proton interactions.\n",
|
|
"\n",
|
|
"We could also add a so-called pairing term, which is a correction term that\n",
|
|
"arises from the tendency of proton pairs and neutron pairs to\n",
|
|
"occur. An even number of particles is more stable than an odd number. \n",
|
|
"\n",
|
|
"\n",
|
|
"### Organizing our data\n",
|
|
"\n",
|
|
"Let us start with reading and organizing our data. \n",
|
|
"We start with the compilation of masses and binding energies from 2016.\n",
|
|
"After having downloaded this file to our own computer, we are now ready to read the file and start structuring our data.\n",
|
|
"\n",
|
|
"\n",
|
|
"We start with preparing folders for storing our calculations and the data file over masses and binding energies. We import also various modules that we will find useful in order to present various Machine Learning methods. Here we focus mainly on the functionality of **scikit-learn**."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 28,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Common imports\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.model_selection import train_test_split\n",
|
|
"from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error\n",
|
|
"import os\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",
|
|
"infile = open(data_path(\"MassEval2016.dat\"),'r')"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Before we proceed, we define also a function for making our plots. You can obviously avoid this and simply set up various **matplotlib** commands every time you need them. You may however find it convenient to collect all such commands in one function and simply call this function."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 29,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"from pylab import plt, mpl\n",
|
|
"plt.style.use('seaborn')\n",
|
|
"mpl.rcParams['font.family'] = 'serif'\n",
|
|
"\n",
|
|
"def MakePlot(x,y, styles, labels, axlabels):\n",
|
|
" plt.figure(figsize=(10,6))\n",
|
|
" for i in range(len(x)):\n",
|
|
" plt.plot(x[i], y[i], styles[i], label = labels[i])\n",
|
|
" plt.xlabel(axlabels[0])\n",
|
|
" plt.ylabel(axlabels[1])\n",
|
|
" plt.legend(loc=0)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Our next step is to read the data on experimental binding energies and\n",
|
|
"reorganize them as functions of the mass number $A$, the number of\n",
|
|
"protons $Z$ and neutrons $N$ using **pandas**. Before we do this it is\n",
|
|
"always useful (unless you have a binary file or other types of compressed\n",
|
|
"data) to actually open the file and simply take a look at it!\n",
|
|
"\n",
|
|
"\n",
|
|
"In particular, the program that outputs the final nuclear masses is written in Fortran with a specific format. It means that we need to figure out the format and which columns contain the data we are interested in. Pandas comes with a function that reads formatted output. After having admired the file, we are now ready to start massaging it with **pandas**. The file begins with some basic format information."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 30,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"\"\"\" \n",
|
|
"This is taken from the data file of the mass 2016 evaluation. \n",
|
|
"All files are 3436 lines long with 124 character per line. \n",
|
|
" Headers are 39 lines long. \n",
|
|
" col 1 : Fortran character control: 1 = page feed 0 = line feed \n",
|
|
" format : a1,i3,i5,i5,i5,1x,a3,a4,1x,f13.5,f11.5,f11.3,f9.3,1x,a2,f11.3,f9.3,1x,i3,1x,f12.5,f11.5 \n",
|
|
" These formats are reflected in the pandas widths variable below, see the statement \n",
|
|
" widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), \n",
|
|
" Pandas has also a variable header, with length 39 in this case. \n",
|
|
"\"\"\""
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The data we are interested in are in columns 2, 3, 4 and 11, giving us\n",
|
|
"the number of neutrons, protons, mass numbers and binding energies,\n",
|
|
"respectively. We add also for the sake of completeness the element name. The data are in fixed-width formatted lines and we will\n",
|
|
"covert them into the **pandas** DataFrame structure."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 31,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Read the experimental data with Pandas\n",
|
|
"Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),\n",
|
|
" names=('N', 'Z', 'A', 'Element', 'Ebinding'),\n",
|
|
" widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),\n",
|
|
" header=39,\n",
|
|
" index_col=False)\n",
|
|
"\n",
|
|
"# Extrapolated values are indicated by '#' in place of the decimal place, so\n",
|
|
"# the Ebinding column won't be numeric. Coerce to float and drop these entries.\n",
|
|
"Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')\n",
|
|
"Masses = Masses.dropna()\n",
|
|
"# Convert from keV to MeV.\n",
|
|
"Masses['Ebinding'] /= 1000\n",
|
|
"\n",
|
|
"# Group the DataFrame by nucleon number, A.\n",
|
|
"Masses = Masses.groupby('A')\n",
|
|
"# Find the rows of the grouped DataFrame with the maximum binding energy.\n",
|
|
"Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"We have now read in the data, grouped them according to the variables we are interested in. \n",
|
|
"We see how easy it is to reorganize the data using **pandas**. If we\n",
|
|
"were to do these operations in C/C++ or Fortran, we would have had to\n",
|
|
"write various functions/subroutines which perform the above\n",
|
|
"reorganizations for us. Having reorganized the data, we can now start\n",
|
|
"to make some simple fits using both the functionalities in **numpy** and\n",
|
|
"**Scikit-Learn** afterwards. \n",
|
|
"\n",
|
|
"Now we define five variables which contain\n",
|
|
"the number of nucleons $A$, the number of protons $Z$ and the number of neutrons $N$, the element name and finally the energies themselves."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 32,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"A = Masses['A']\n",
|
|
"Z = Masses['Z']\n",
|
|
"N = Masses['N']\n",
|
|
"Element = Masses['Element']\n",
|
|
"Energies = Masses['Ebinding']\n",
|
|
"print(Masses)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The next step, and we will define this mathematically later, is to set up the so-called **design matrix**. We will throughout call this matrix $\\boldsymbol{X}$.\n",
|
|
"It has dimensionality $p\\times n$, where $n$ is the number of data points and $p$ are the so-called predictors. In our case here they are given by the number of polynomials in $A$ we wish to include in the fit."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 33,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Now we set up the design matrix X\n",
|
|
"X = np.zeros((len(A),5))\n",
|
|
"X[:,0] = 1\n",
|
|
"X[:,1] = A\n",
|
|
"X[:,2] = A**(2.0/3.0)\n",
|
|
"X[:,3] = A**(-1.0/3.0)\n",
|
|
"X[:,4] = A**(-1.0)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"With **scikitlearn** we are now ready to use linear regression and fit our data."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 34,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"clf = skl.LinearRegression().fit(X, Energies)\n",
|
|
"fity = clf.predict(X)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Pretty simple! \n",
|
|
"Now we can print measures of how our fit is doing, the coefficients from the fits and plot the final fit together with our data."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 35,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"# The mean squared error \n",
|
|
"print(\"Mean squared error: %.2f\" % mean_squared_error(Energies, fity))\n",
|
|
"# Explained variance score: 1 is perfect prediction \n",
|
|
"print('Variance score: %.2f' % r2_score(Energies, fity))\n",
|
|
"# Mean absolute error \n",
|
|
"print('Mean absolute error: %.2f' % mean_absolute_error(Energies, fity))\n",
|
|
"print(clf.coef_, clf.intercept_)\n",
|
|
"\n",
|
|
"Masses['Eapprox'] = fity\n",
|
|
"# Generate a plot comparing the experimental with the fitted values values.\n",
|
|
"fig, ax = plt.subplots()\n",
|
|
"ax.set_xlabel(r'$A = N + Z$')\n",
|
|
"ax.set_ylabel(r'$E_\\mathrm{bind}\\,/\\mathrm{MeV}$')\n",
|
|
"ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,\n",
|
|
" label='Ame2016')\n",
|
|
"ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',\n",
|
|
" label='Fit')\n",
|
|
"ax.legend()\n",
|
|
"save_fig(\"Masses2016\")\n",
|
|
"plt.show()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### Seeing the wood for the trees\n",
|
|
"\n",
|
|
"As a teaser, let us now see how we can do this with decision trees using **scikit-learn**. Later we will switch to so-called **random forests**!"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 36,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"\n",
|
|
"#Decision Tree Regression\n",
|
|
"from sklearn.tree import DecisionTreeRegressor\n",
|
|
"regr_1=DecisionTreeRegressor(max_depth=5)\n",
|
|
"regr_2=DecisionTreeRegressor(max_depth=7)\n",
|
|
"regr_3=DecisionTreeRegressor(max_depth=9)\n",
|
|
"regr_1.fit(X, Energies)\n",
|
|
"regr_2.fit(X, Energies)\n",
|
|
"regr_3.fit(X, Energies)\n",
|
|
"\n",
|
|
"\n",
|
|
"y_1 = regr_1.predict(X)\n",
|
|
"y_2 = regr_2.predict(X)\n",
|
|
"y_3=regr_3.predict(X)\n",
|
|
"Masses['Eapprox'] = y_3\n",
|
|
"# Plot the results\n",
|
|
"plt.figure()\n",
|
|
"plt.plot(A, Energies, color=\"blue\", label=\"Data\", linewidth=2)\n",
|
|
"plt.plot(A, y_1, color=\"red\", label=\"max_depth=5\", linewidth=2)\n",
|
|
"plt.plot(A, y_2, color=\"green\", label=\"max_depth=7\", linewidth=2)\n",
|
|
"plt.plot(A, y_3, color=\"m\", label=\"max_depth=9\", linewidth=2)\n",
|
|
"\n",
|
|
"plt.xlabel(\"$A$\")\n",
|
|
"plt.ylabel(\"$E$[MeV]\")\n",
|
|
"plt.title(\"Decision Tree Regression\")\n",
|
|
"plt.legend()\n",
|
|
"save_fig(\"Masses2016Trees\")\n",
|
|
"plt.show()\n",
|
|
"print(Masses)\n",
|
|
"print(np.mean( (Energies-y_1)**2))"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### And what about using neural networks?\n",
|
|
"\n",
|
|
"The **seaborn** package allows us to visualize data in an efficient way. Note that we use **scikit-learn**'s multi-layer perceptron (or feed forward neural network) \n",
|
|
"functionality."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 37,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"from sklearn.neural_network import MLPRegressor\n",
|
|
"from sklearn.metrics import accuracy_score\n",
|
|
"import seaborn as sns\n",
|
|
"\n",
|
|
"X_train = X\n",
|
|
"Y_train = Energies\n",
|
|
"n_hidden_neurons = 100\n",
|
|
"epochs = 100\n",
|
|
"# store models for later use\n",
|
|
"eta_vals = np.logspace(-5, 1, 7)\n",
|
|
"lmbd_vals = np.logspace(-5, 1, 7)\n",
|
|
"# store the models for later use\n",
|
|
"DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n",
|
|
"train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n",
|
|
"sns.set()\n",
|
|
"for i, eta in enumerate(eta_vals):\n",
|
|
" for j, lmbd in enumerate(lmbd_vals):\n",
|
|
" dnn = MLPRegressor(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n",
|
|
" alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n",
|
|
" dnn.fit(X_train, Y_train)\n",
|
|
" DNN_scikit[i][j] = dnn\n",
|
|
" train_accuracy[i][j] = dnn.score(X_train, Y_train)\n",
|
|
"\n",
|
|
"fig, ax = plt.subplots(figsize = (10, 10))\n",
|
|
"sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
|
|
"ax.set_title(\"Training Accuracy\")\n",
|
|
"ax.set_ylabel(\"$\\eta$\")\n",
|
|
"ax.set_xlabel(\"$\\lambda$\")\n",
|
|
"plt.show()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## A first summary\n",
|
|
"\n",
|
|
"The aim behind these introductory words was to present to you various\n",
|
|
"Python libraries and their functionalities, in particular libraries like\n",
|
|
"**numpy**, **pandas**, **xarray** and **matplotlib** and other that make our life much easier\n",
|
|
"in handling various data sets and visualizing data. \n",
|
|
"\n",
|
|
"Furthermore,\n",
|
|
"**Scikit-Learn** allows us with few lines of code to implement popular\n",
|
|
"Machine Learning algorithms for supervised learning. Later we will meet **Tensorflow**, a powerful library for deep learning. \n",
|
|
"Now it is time to dive more into the details of various methods. We will start with linear regression and try to take a deeper look at what it entails.\n",
|
|
"\n",
|
|
"\n",
|
|
"# Review of Basic Statistics"
|
|
]
|
|
}
|
|
],
|
|
"metadata": {},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 2
|
|
}
|