Newer
Older
"# IGNORE THIS CELL WHICH CUSTOMIZES LAYOUT AND STYLING OF THE NOTEBOOK !\n",
"%matplotlib inline\n",
"%config InlineBackend.figure_format = 'retina'\n",
"import warnings\n",
"\n",
"import matplotlib.pyplot as plt\n",
"\n",
"warnings.filterwarnings(\"ignore\", category=FutureWarning)\n",
"warnings.filterwarnings(\"ignore\", message=\"X does not have valid feature names, but [a-zA-Z]+ was fitted with feature names\", category=UserWarning)\n",
" \n",
"from IPython.core.display import HTML\n",
"\n",
"HTML(open(\"custom.html\", \"r\").read())"
"# Chapter 1: General Introduction to machine learning (ML)"
"A \"model\" allows us to explain observations and to answer questions. For example:\n",
"\n",
" 1. Where will my car at given velocity stop if I apply break now?\n",
" 2. Where on the night sky will I see the moon tonight?\n",
" 3. Is the email I received spam?\n",
"- The first two questions can be answered based on existing physical models (formulas). \n",
"\n",
"- For the questions 3 and 4 it is difficult to develop explicitly formulated models. \n",
"- We have a vague understanding of the problem domain, e.g. we know that some words are specific to spam emails and others are specific to my personal and work-related emails.\n",
"- We have enough example data, as my mailbox is full of both spam and non-spam emails.\n",
"\n",
"\n",
"We could handcraft a personal spam classifier by hard coding rules, like _\"mail contains 'no prescription' and comes from russia or china\"_, plus some statistics. This would be very tedious.\n",
"\n",
"<div class=\"alert alert-block alert-info\">\n",
"<i class=\"fa fa-info-circle\"></i>\n",
" Systems with such hard coded rules are called <strong>expert systems</strong>\n",
"</div>\n",
"\n",
"In such cases machine learning is a better approach.\n",
"<div class=\"alert alert-block alert-warning\">\n",
"<i class=\"fa fa-info-circle\"></i>\n",
"<strong>Machine learning</strong> offers approaches to automatically build predictive models based on example data.\n",
"</div>\n",
"<div class=\"alert alert-block alert-info\">\n",
"<i class=\"fa fa-info-circle\"></i>\n",
"The closely-related concept of <strong>data mining</strong> usually means use of predictive machine learning models to explicitly discover previously unknown knowledge from a specific data set, such as, for instance, association rules between customer and article types in the Problem 4 above.\n",
"\n",
"\n",
"\n",
"## ML: what is \"learning\" ?\n",
"\n",
"To create a predictive model, we must first **train** such a model on given data. \n",
"<div class=\"alert alert-block alert-info\">\n",
"<i class=\"fa fa-info-circle\"></i>\n",
"Alternative names for \"to train\" a model are \"to <strong>fit</strong>\" or \"to <strong>learn</strong>\" a model.\n",
"</div>\n",
"All ML algorithms have in common that they rely on internal data structures and/or parameters.\n",
"\n",
"<div class=\"alert alert-block alert-warning\">\n",
"<i class=\"fa fa-info-circle\"></i>\n",
"<strong>Learning</strong> builds up internal data structures or adjusts parameters of a ML method, based on the given data.\n",
"</div>\n",
"\n",
"After ML method has learned the data, it can be used to explain observations or to answer questions.\n",
"\n",
"The important difference between explicit models and models learned from data:\n",
"\n",
"- Explicit models usually offer exact answers to questions, whereas\n",
"- Models that learn from data usually come with inherent uncertainty.\n",
"\n",
"\n",
"A machine-learning algorithm usually adapts *(internal) parameters* to the training data set during learning. But the working of such algorithms can also be adjusted by changing the so-called *hyperparameters*. To summarize:\n",
"- *parameters* are what an ML algorithm learns from training data.\n",
"- *hyper parameters* control **how** an ML algorithm learns."
"Some parts of ML are older than you might think. This is a rough time line with a few selected achievements from this field:\n",
" 1805: Least squares regression\n",
" 1812: Bayes' rule\n",
" 1957-65: \"k-means\" clustering algorithm\n",
" 1959: Term \"machine learning\" is coined by Arthur Samuel, an AI pioneer\n",
" 1969: Book \"Perceptrons\": Limitations of Neural Networks\n",
" 1974-86: Neural networks learning breakthrough: backpropagation method\n",
" 1984: Book \"Classification And Regression Trees\"\n",
" 1995: Randomized Forests and Support Vector Machines methods\n",
" 1998: Public appearance: first ML implementations of spam filtering methods; naive Bayes Classifier method\n",
" 2006-12: Neural networks learning breakthrough: deep learning\n",
" \n",
"So the field is not as new as one might think, but due to \n",
"\n",
"- more available data\n",
"- more processing power \n",
"- development of better algorithms \n",
"\n",
"more applications of machine learning appeared during the last 15 years."
"source": [
"## Machine learning with Python\n",
"\n",
"Currently (as of 2019) `Python` is the dominant programming language for ML. Especially the advent of deep-learning pushed this forward. First versions of frameworks such as `TensorFlow` or `PyTorch` got early `Python` releases.\n",
"\n",
"The prevalent packages in the Python eco-system used for ML include:\n",
"\n",
"- `pandas` for handling tabular data\n",
"- `matplotlib` and `seaborn` for plotting\n",
"- `scikit-learn` for classical (non-deep-learning) ML\n",
"- `TensorFlow`, `PyTorch` and `Keras` for deep-learning.\n",
"\n",
"`scikit-learn` is very comprehensive and the online-documentation itself provides a good introducion into ML."
"## ML lingo: What are \"features\" ?\n",
"A typical and very common situation is that our data is presented as a table, as in the following example:"
"features = pd.read_csv(\"data/beers.csv\")\n",
"<div class=\"alert alert-block alert-warning\">\n",
"<i class=\"fa fa-warning\"></i> <strong>Definitions</strong>\n",
"<ul>\n",
" <li>every row of such a matrix is called a <strong>sample</strong> or <strong>feature vector</strong>;</li>\n",
" <li>the cells in a row are <strong>feature values</strong>;</li>\n",
" <li>every column name is called a <strong>feature name</strong> or <strong>attribute</strong>.</li>\n",
"</ul>\n",
"\n",
"Features are also commonly called <strong>variables</strong>.\n",
"</div>"
"The feature names are `alcohol_content`, `bitterness`, `darkness`, `fruitiness` and `is_yummy`.\n",
"<div class=\"alert alert-block alert-warning\">\n",
"<i class=\"fa fa-warning\"></i> <strong>More definitions</strong>\n",
"<ul>\n",
" <li>The first four features have continuous numerical values within some ranges - these are called <strong>numerical features</strong>,</li>\n",
" <li>the <code>is_yummy</code> feature has only a finite set of values (\"categories\"): <code>0</code> (\"no\") and <code>1</code> (\"yes\") - this is called a <strong>categorical feature</strong>.</li>\n",
"A straight-forward application of machine-learning on the previous beer dataset is: **\"can we predict `is_yummy` from the other features\"** ?\n",
"<div class=\"alert alert-block alert-warning\">\n",
"<i class=\"fa fa-warning\"></i> <strong>Even more definitions</strong>\n",
"\n",
"In context of the question above we call:\n",
"<ul>\n",
" <li>the <code>alcohol_content</code>, <code>bitterness</code>, <code>darkness</code>, <code>fruitiness</code> features our <strong>input features</strong>, and</li>\n",
" <li>the <code>is_yummy</code> feature our <strong>target/output feature</strong> or a <strong>label</strong> of our data samples.\n",
" <ul>\n",
" <li>Values of categorical labels, such as <code>0</code> (\"no\") and <code>1</code> (\"yes\") here, are often called <strong>classes</strong>.</li>\n",
" </ul>\n",
" </li>\n",
"This is how feature matrices look like in general:\n",
"\n",
"### Most of the machine learning algorithms require that every sample is represented as a vector containing numbers. \n",
"\n",
"Let's look now at two examples of how one can create feature vectors from data which is not naturally given as vectors:\n",
"\n",
"1. Feature vectors from images\n",
"2. Feature vectors from text.\n",
"### 1st Example: How to represent images as feature vectors?\n",
"In order to simplify our explanations we only consider grayscale images in this section. \n",
"Computers represent images as matrices. Every cell in the matrix represents one pixel, and the numerical value in the matrix cell its gray value.\n",
"So how can we represent images as vectors?\n",
"To demonstrate this we will now load a sample dataset that is included in `scikit-learn`:"
"from sklearn.datasets import load_digits\n",
"\n",
"Let's plot the first ten digits from this data set:"
"import matplotlib.pyplot as plt\n",
"\n",
"# dd.images: list of 8 x 8 images\n",
"# dd.target: label\n",
"\n",
" plt.subplot(1, N, i + 1).set_title(dd.target[i])\n",
"The data is a set of 8 x 8 matrices with values 0 to 15 (black to white). The range 0 to 15 is fixed for this specific data set. Other formats allow e.g. values 0..255 or floating point values in the range 0 to 1."
"print(\"images[0].shape:\", dd.images[0].shape) # dimensions of a first sample array\n",
"print(\"images[0]:\\n\", dd.images[0]) # first sample array"
"To transform such an image to a feature vector we just have to flatten the matrix by concatenating the rows to one single vector of size 64:"
"image_vector = dd.images[0].flatten()\n",
"print(\"image_vector.shape:\", image_vector.shape)\n",
"print(\"image_vector:\", image_vector)"
"source": [
"<br/>\n",
"\n",
"This is how the final feature matrix then looks like:\n",
"\n",
"<img src=\"images/feature_matrix_mnist.png\" width=50%/>"
"### 2nd Example: How to present textual data as feature vectors?"
"- If we start a machine learning project for texts, we first have to choose a dictionary (a set of words) for this project. \n",
"- The words in the dictionary are numbered / have an index. \n",
"- The final representation of a text as a feature vector depends on this dictionary.\n",
"\n",
"Such a dictionary can be very large, but for the sake of simplicity we use a very small enumerated dictionary to explain the overall procedure:\n",
"\n",
"\n",
"| Word | Index |\n",
"|----------|-------|\n",
"| like | 0 |\n",
"| dislike | 1 |\n",
"| american | 2 |\n",
"| italian | 3 |\n",
"| beer | 4 |\n",
"| pizza | 5 |\n",
"\n",
"To \"vectorize\" a given text we count the words in the text which also exist in the vocabulary and put the counts at the given `Index`.\n",
"\n",
"E.g. `\"I dislike american pizza, but american beer is nice\"`:\n",
"\n",
"| dislike | 1 | 1 |\n",
"| american | 2 | 2 |\n",
"| italian | 3 | 0 |\n",
"| beer | 4 | 1 |\n",
"| pizza | 5 | 1 |\n",
"\n",
"The respective feature vector is the `Count` column, which is:\n",
"In real case scenarios the dictionary is much bigger, which often results in vectors with only few non-zero entries (so called **sparse vectors**)."
"Below you find is a short code example to demonstrate how text feature vectors can be created with `scikit-learn`.\n",
"<div class=\"alert alert-block alert-info\">\n",
"<i class=\"fa fa-info-circle\"></i>\n",
"Such vectorization is usually not done manually. Actually there are improved but more complicated procedures which compute multiplicative weights for the vector entries to emphasize informative words such as, e.g., <a href=\"https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html\">\"term frequency-inverse document frequency\" vectorizer</a>.\n",
"</div>"
"source": [
"from sklearn.feature_extraction.text import CountVectorizer\n",
"\n",
"vocabulary = {\n",
" \"like\": 0,\n",
" \"dislike\": 1,\n",
" \"american\": 2,\n",
" \"italian\": 3,\n",
" \"beer\": 4,\n",
" \"pizza\": 5,\n",
"}\n",
"# this how one can create a count vector for a given piece of text:\n",
"vector = (\n",
" vectorizer.fit_transform([\"I dislike american pizza. But american beer is nice\"])\n",
" .toarray()\n",
" .flatten()\n",
")\n",
"source": [
"<br/>\n",
"The corresponding feautre matrix then has the form:\n",
"<img src=\"images/feature_matrix_document.png\" width=70% />"
"## One hot encoding \n",
"The so called **one-hot-encoding** is a method to encode categorial features. \n",
"Let's assume our beer data set has an extra column to encode the beer style:"
"cell_type": "code",
Mikolaj Rybinski
committed
"execution_count": null,
"pd.read_csv(\"data/beers_with_style.csv\").head()"
},
{
"cell_type": "markdown",
"source": [
"The style column can take three different values: `pilsener`, `ale` and `stout`.\n",
"\n",
"To apply *one-hot-encoding* we replace the column `style` by three new columns `is_pilsener`, `is_ale` and `is_stout`:"
Mikolaj Rybinski
committed
"execution_count": null,
"source": [
"pd.read_csv(\"data/beers_with_one_hot_encoding.csv\").head()"
},
{
"cell_type": "markdown",
"source": [
"As you can see\n",
"- the new columns only have values `0` or `1`\n",
"- for each row exactly one entry of `is_pilsener`, `is_ale` and `is_stout` is `1`, all others are `0`."
},
{
"cell_type": "markdown",
"source": [
"<div class=\"alert alert-block alert-info\">\n",
"<i class=\"fa fa-info-circle\"></i>\n",
"We will later see that <code>scikit-learn</code> has functions to transform categorical data into an appropriate one-hot-encoding.\n",
"</div>"
},
"Most applications of ML belong to two categories: **supervised** and **unsupervised** learning.\n",
"In supervised learning the data comes with an additional target/label value that we want to predict. Such a problem can be either \n",
"\n",
"- **classification**: we want to predict a categorical value.\n",
"- **regression**: we want to predict numbers in a given range.\n",
"Examples of supervised learning:\n",
"- Classification: predict the class `is_yummy` based on the attributes `alcohol_content`,\t`bitterness`, \t`darkness` and `fruitiness` (a standard two-class problem).\n",
"\n",
"- Classification: predict the digit-shown based on a 8 x 8 pixel image (a multi-class problem).\n",
"\n",
"- Regression: predict temperature based on how long sun was shining in the last 10 minutes.\n",
"\n",
"<table>\n",
" <tr>\n",
" <td><img src=\"./images/classification-svc-2d-poly.png\" width=400px></td>\n",
" <td><img src=\"./images/regression-lin-1d.png\" width=400px></td>\n",
" </tr>\n",
" <tr>\n",
" <td><center>Classification</center></td>\n",
" <td><center>Linear regression</center></td>\n",
" </tr>\n",
"</table>\n"
"In unsupervised learning the training data consists of samples without any corresponding target/label values and the aim is to find structure in data. Some common applications are:\n",
"- Density estimation, novelty detection: find a probability distribution in your data.\n",
"- Dimension reduction (e.g. PCA): find latent structures in your data.\n",
"\n",
"Examples of unsupervised learning:\n",
"- Can we split up our beer data set into sub-groups of similar beers?\n",
"- Can we reduce our data set because groups of features are somehow correlated?\n",
" <td><img src=\"./images/cluster-image.png/\" width=400px></td>\n",
" <td><img src=\"./images/nonlin-pca.png/\" width=400px></td>\n",
" </tr>\n",
" <tr>\n",
" <td><center>Clustering</center></td>\n",
" <td><center>Dimension reduction: detecting 2D structure in 3D data</center></td>\n",
" </tr>\n",
"</table>\n",
"\n",
"\n",
"\n",
"This course will only introduce concepts and methods from **supervised learning**."
"## How to apply machine learning in practice?\n",
"\n",
"Application of machine learning in practice consists of several phases:\n",
"\n",
"1. Understand and clean your data\n",
"2. Analyze model for its quality / performance\n",
"2. Apply this model to new incoming data\n",
"\n",
"In practice steps 1. and 2. are iterated for different machine learning algorithms with different configurations until performance is optimal or sufficient. \n",
"\n",
"\n",
"<div class=\"alert alert-block alert-warning\">\n",
"<i class=\"fa fa-warning\"></i> <strong>Garbage in / garbage out</strong>\n",
"\n",
"The principle of \"garbage in, garbage out\" also applies in machine learning.\n",
"\n",
"Cleaning data to remove strong outliers or erroneous entries is crucial in real-world problems and can be the most time-consuming part.\n",
"\n",
"</div>"
"\n",
"\n",
"<a href='https://imgflip.com/i/303yin'><img src=\"./images/303yin.jpg\" width=35%/></a><br/><a href='https://imgflip.com/gif-maker'> via Imgflip GIF Maker</a> "
"source": [
"Our example beer data set reflects the very personal opinion of one of the tutors which beer he likes and which not. To learn a predictive model and to understand influential factors all beers went through some lab analysis to measure alcohol content, bitterness, darkness and fruitiness."
{
"cell_type": "markdown",
"### Step 1: Load the data and show the overall structure using `pandas`"
"source": [
"import pandas as pd\n",
"\n",
"# read some data\n",
"beer_data = pd.read_csv(\"data/beers.csv\")\n",
"print(beer_data.shape)"
"# show first 5 rows\n",
"source": [
"# show basic statistics of the data\n",
"beer_data.describe()"
},
{
"cell_type": "markdown",
"### Step 2: Visualy inspect data using `seaborn`\n",
"\n",
"Such checks are very useful before you start throwning ML on your data. Some vague understanding how features are distributed and correlate can later be very helpfull to optimize performance of ML procedures.\n",
"\n"
"sns.set(style=\"ticks\")\n",
"\n",
"for_plot = beer_data.copy()\n",
"\n",
" # seaborn has issues if labes are numbers or strings which represent numbers,\n",
" # for whatever reason \"real\" text labels work\n",
" return \"no\" if value == 0 else \"yes\"\n",
"for_plot[\"is_yummy\"] = for_plot[\"is_yummy\"].apply(translate_label)\n",
"\n",
"sns.pairplot(for_plot, hue=\"is_yummy\", diag_kind=\"hist\", diag_kws=dict(alpha=0.5));"
"What do we see?\n",
"\n",
"- Points and colors don't look randomly distributed.\n",
"- We can see that some pairs like `darkness` vs `bitterness` seem to carry information which could support building a classifier.\n",
"- We also see that `bitterness` and `fruitiness` show correlation.\n",
"- We see slightly different distributions for features for each class.\n",
"\n",
"Features which show no structure can also decrease performance of ML and often it makes sense to discard them.\n"
"### Step 3: Prepare data: split features and labels"
"# all columns up to the last one:\n",
"input_features = beer_data.iloc[:, :-1]\n",
"\n",
"# only the last column:\n",
"print(input_features.shape)\n",
"print(labels.head(5))\n",
"### Step 4: Start machine learning using `scikit-learn`"
},
{
"cell_type": "markdown",
"Let's finally do some machine learning starting with the so called `LogisticRegression` classifier from `scikit-learn` package. The intention here is to experiment first. Details of this and further ML algorithms are not necessary at this point, but do not worry, they will come later during the course.\n",
"\n",
"<div class=\"alert alert-block alert-info\">\n",
"<i class=\"fa fa-info-circle\"></i>\n",
"<code>LogisticRegression</code> is a classification method, even so the name contains \"regression\"-as the other group of unsupervised learning methods. In fact, in logistic regression method the (linear) regression is used internally and the result is then transformed (using logistic function) to probability of belonging to one of the two classes.\n",
"from sklearn.linear_model import LogisticRegression\n",
"classifier = LogisticRegression()\n",
"classifier"
"<div class=\"alert alert-block alert-warning\">\n",
"<i class=\"fa fa-warning\"></i> <strong>Built-in documentation</strong>\n",
"\n",
"If you want to learn more about <code>LogisticRegression</code> you can use <code>help(LogisticRegression)</code> or <code>?LogisticRegression</code> to see the related documenation. The latter version works only in Jupyter Notebooks (or in IPython shell).\n",
"</div>"
"<div class=\"alert alert-block alert-warning\">\n",
" <i class=\"fa fa-warning\"></i> <strong><code>scikit-learn</code> API</strong>\n",
"In <code>scikit-learn</code> all classifiers have:\n",
"<ul>\n",
" <li>a <strong><code>fit()</code></strong> method to learn from data, and</li>\n",
" <li>and a subsequent <strong><code>predict()</code></strong> method for predicting classes from input features.</li>\n",
"</ul>\n",
"</div>"
"# Sanity check: can't predict if not fitted (trained)\n",
"classifier.predict(input_features)"
"# Fit\n",
"classifier.fit(input_features, labels)\n",
"\n",
"# Predict\n",
"predicted_labels = classifier.predict(input_features)\n",
"print(predicted_labels.shape)"
"Here we've just re-classified our training data. Lets check our result with a few examples:"
"for i in range(3):\n",
" print(labels[i], \"predicted as\", predicted_labels[i])"
"What, \"0 predicted as 1\"? This looks suspicious!\n",
"source": [
"print(len(labels), \"examples\")\n",
"print(sum(predicted_labels == labels), \"labeled correctly\")"
"<div class=\"alert alert-block alert-info\">\n",
"<i class=\"fa fa-info-circle\"></i>\n",
"<code>predicted_labels == labels</code> evaluates to a vector of <code>True</code> or <code>False</code> Boolean values. When used as numbers, Python handles <code>True</code> as <code>1</code> and <code>False</code> as <code>0</code>. So, <code>sum(...)</code> simply counts the correctly predicted labels.\n",
"<div style=\"font-weight: bold; font-size: 200%;\">What happened?</div>\n",
"Why were not all labels predicted correctly?\n",
"\n",
"Neither `Python` nor `scikit-learn` is broken. What we observed above is very typical for machine-learning applications.\n",
"\n",
"Reasons could be:\n",
"- we have incomplete information: other features of beer which also contribute to the rating (like \"maltiness\") were not measured or can not be measured. \n",
"- the used classifiers might have been not suitable for the given problem.\n",
"- noise in the data as incorrectly assigned labels also affect results.\n",
"**Finding sufficient features and clean data is crucial for the performance of ML algorithms!**\n",
"\n",
"Another important requirement is to make sure that you have clean data: input-features might be corrupted by flawed entries, feeding such data into a ML algorithm will usually lead to reduced performance."
"### Compare with alternative machine learning method from `scikit-learn`"
"Now, using previously loaded and prepared beer data, train a different `scikit-learn` classifier - the so called **Support Vector Classifier** `SVC`, and evaluate its \"re-classification\" performance again.\n",
"\n",
"<div class=\"alert alert-block alert-info\">\n",
"<i class=\"fa fa-info-circle\"></i>\n",
"<code>SVC</code> belongs to a class of algorithms named \"Support Vector Machines\" (SVMs). Again, it will be discussed in more detail in the following scripts.\n",
"source": [
"from sklearn.svm import SVC\n",
"classifier = SVC()\n",
"classifier.fit(input_features, labels)\n",
"\n",
"predicted_labels = classifier.predict(input_features)\n",
"\n",
"print(len(labels), \"examples\")\n",
"print(sum(predicted_labels == labels), \"labeled correctly\")"
"<div class=\"alert alert-block alert-info\">\n",
"<i class=\"fa fa-info-circle\"></i>\n",
"Better re-classification in our example does not indicate here that <code>SVC</code> is better than <code>LogisticRegression</code> in all cases. The performance of a classifier strongly depends on the data set.\n",
"</div>\n",
"\n",
"\n"
},
{
"cell_type": "markdown",
"### Experiment with hyperparameters of ML methods"
},
{
"cell_type": "markdown",
"Both `LogisticRegression` and `SVC` classifiers have a hyperparameter `C` which allows to enforce a \"simplification\" (often called **regularization**) of the resulting model. Test the beers data \"re-classification\" with different values of this parameter. "