"README.md" did not exist on "e4bae36dd58cc8c5205d4b06b41920c02ce61636"
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",
"from IPython.core.display import HTML\n",
"\n",
"HTML(open(\"custom.html\", \"r\").read())"
"# Chapter 1: General Introduction to machine learning (ML)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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."
]
},
{
"cell_type": "markdown",
"metadata": {},
"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."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 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",
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<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>"
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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",
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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",
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This is how feature matrices look like in general:\n",
"\n",
"<img src=\"images/feature_matrix.png\" width=50%/>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 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",
"metadata": {
"scrolled": true
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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",
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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)"
{
"cell_type": "markdown",
"metadata": {},
"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?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- 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**)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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",
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<br/>\n",
"The corresponding feautre matrix then has the form:\n",
"<img src=\"images/feature_matrix_document.png\" width=70% />"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 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",
"execution_count": 25,
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>alcohol_content</th>\n",
" <th>bitterness</th>\n",
" <th>darkness</th>\n",
" <th>fruitiness</th>\n",
" <th>style</th>\n",
" <th>is_yummy</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>3.739295</td>\n",
" <td>0.422503</td>\n",
" <td>0.989463</td>\n",
" <td>0.215791</td>\n",
" <td>pilsener</td>\n",
" <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>4.207849</td>\n",
" <td>0.841668</td>\n",
" <td>0.928626</td>\n",
" <td>0.380420</td>\n",
" <td>ale</td>\n",
" <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>4.709494</td>\n",
" <td>0.322037</td>\n",
" <td>5.374682</td>\n",
" <td>0.145231</td>\n",
" <td>stout</td>\n",
" <td>1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>4.684743</td>\n",
" <td>0.434315</td>\n",
" <td>4.072805</td>\n",
" <td>0.191321</td>\n",
" <td>pilsener</td>\n",
" <td>1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>4.148710</td>\n",
" <td>0.570586</td>\n",
" <td>1.461568</td>\n",
" <td>0.260218</td>\n",
" <td>ale</td>\n",
" <td>0</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" alcohol_content bitterness darkness fruitiness style is_yummy\n",
"0 3.739295 0.422503 0.989463 0.215791 pilsener 0\n",
"1 4.207849 0.841668 0.928626 0.380420 ale 0\n",
"2 4.709494 0.322037 5.374682 0.145231 stout 1\n",
"3 4.684743 0.434315 4.072805 0.191321 pilsener 1\n",
"4 4.148710 0.570586 1.461568 0.260218 ale 0"
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pd.read_csv(\"data/beers_with_style.csv\").head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"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`:"
"execution_count": 31,
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>alcohol_content</th>\n",
" <th>bitterness</th>\n",
" <th>darkness</th>\n",
" <th>fruitiness</th>\n",
" <th>is_ale</th>\n",
" <th>is_pilsener</th>\n",
" <th>is_stout</th>\n",
" <th>is_yummy</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>3.739295</td>\n",
" <td>0.422503</td>\n",
" <td>0.989463</td>\n",
" <td>0.215791</td>\n",
" <td>0</td>\n",
" <td>1</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>4.207849</td>\n",
" <td>0.841668</td>\n",
" <td>0.928626</td>\n",
" <td>0.380420</td>\n",
" <td>1</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>4.709494</td>\n",
" <td>0.322037</td>\n",
" <td>5.374682</td>\n",
" <td>0.145231</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>1</td>\n",
" <td>1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>4.684743</td>\n",
" <td>0.434315</td>\n",
" <td>4.072805</td>\n",
" <td>0.191321</td>\n",
" <td>0</td>\n",
" <td>1</td>\n",
" <td>0</td>\n",
" <td>1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>4.148710</td>\n",
" <td>0.570586</td>\n",
" <td>1.461568</td>\n",
" <td>0.260218</td>\n",
" <td>1</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" alcohol_content bitterness darkness fruitiness is_ale is_pilsener \\\n",
"0 3.739295 0.422503 0.989463 0.215791 0 1 \n",
"1 4.207849 0.841668 0.928626 0.380420 1 0 \n",
"2 4.709494 0.322037 5.374682 0.145231 0 0 \n",
"3 4.684743 0.434315 4.072805 0.191321 0 1 \n",
"4 4.148710 0.570586 1.461568 0.260218 1 0 \n",
"\n",
" is_stout is_yummy \n",
"0 0 0 \n",
"1 0 0 \n",
"2 1 1 \n",
"3 0 1 \n",
"4 0 0 "
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pd.read_csv(\"data/beers_with_one_hot_encoding.csv\").head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"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",
"metadata": {},
"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>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Unsupervised learning \n",
"\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**."
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 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>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"./images/303yin.jpg\" width=35%/>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"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",
"metadata": {},
"source": [
"### Step 1: Load the data and show the overall structure using `pandas`"
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"\n",
"# read some data\n",
"beer_data = pd.read_csv(\"data/beers.csv\")\n",
"print(beer_data.shape)"
]
},
"execution_count": null,
"metadata": {},
"outputs": [],
"# show first 5 rows\n",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# show basic statistics of the data\n",
"beer_data.describe()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 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));"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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"
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 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",
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Step 4: Start machine learning using `scikit-learn`"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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"