"If we start a machine learning project for texts, we first have to choose a dictionary - set of words for this project. The final representation of a text as a feature vector depends on this dictionary.\n",
"If we start a machine learning project for texts, we first have to choose a dictionary (a set of words) for this project. The words in the dictionary are enumerated. 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",
...
...
@@ -582,6 +558,11 @@
"source": [
"## ML lingo: What are the different types of datasets?\n",
"\u001b[0;32m<ipython-input-15-9e1ed3d39774>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# Sanity check: can't predict if not fitted (trained)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mclassifier\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpredict\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minput_features\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"Better re-classification does not indicate here that <code>SVC</code> is better than <code>LogisticRegression</code>. At most it seems to fit better to our training data. We will learn later that this may be actually not a good thing.\n",
"</div>\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"
]
},
{
...
...
@@ -1383,12 +1361,15 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Both `LogisticRegression` and `SVC` classifiers have a parameter `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.\n"
"Both `LogisticRegression` and `SVC` classifiers have a parameter `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.\n",
"\n",
"\n",
"**TOBE discussed**: is \"regularization\" to technical here ? decision surfaces and details of classifers come later. Original purpose (Uwe) was to demonstrate that classifiers can be tuned to the data set."
]
},
{
"cell_type": "code",
"execution_count": 19,
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
...
...
@@ -1409,7 +1390,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"# Exercise section 3 (optional)"
"# Exercise section 2 (optional)"
]
},
{
...
...
@@ -1433,7 +1414,7 @@
},
{
"cell_type": "code",
"execution_count": 20,
"execution_count": 21,
"metadata": {},
"outputs": [
{
...
...
@@ -1459,7 +1440,7 @@
},
{
"cell_type": "code",
"execution_count": 21,
"execution_count": 22,
"metadata": {},
"outputs": [
{
...
...
@@ -1551,7 +1532,7 @@
"4 0 "
]
},
"execution_count": 21,
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
...
...
@@ -1565,7 +1546,7 @@
},
{
"cell_type": "code",
"execution_count": 22,
"execution_count": 23,
"metadata": {},
"outputs": [
{
...
...
@@ -1687,7 +1668,7 @@
"max 2.500000 2.000000 "
]
},
"execution_count": 22,
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
...
...
@@ -1698,7 +1679,7 @@
},
{
"cell_type": "code",
"execution_count": 23,
"execution_count": 24,
"metadata": {},
"outputs": [
{
...
...
@@ -1739,16 +1720,16 @@
},
{
"cell_type": "code",
"execution_count": 24,
"execution_count": 25,
"metadata": {
"collapsed": true
"scrolled": true
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/mikolajr/Workspace/SSDM/machinelearning-introduction-workshop/.venv/lib/python3.7/site-packages/ipykernel_launcher.py:9: UserWarning: get_ipython_dir has moved to the IPython.paths module since IPython 4.0.\n",
"/Users/uweschmitt/Projects/machinelearning-introduction-workshop/venv3.6/lib/python3.6/site-packages/ipykernel_launcher.py:9: UserWarning: get_ipython_dir has moved to the IPython.paths module since IPython 4.0.\n",
" if __name__ == '__main__':\n"
]
},
...
...
@@ -1853,7 +1834,7 @@
"<IPython.core.display.HTML object>"
]
},
"execution_count": 24,
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
...
...
@@ -1983,7 +1964,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.1"
"version": "3.6.6"
}
},
"nbformat": 4,
...
...
%% Cell type:markdown id: tags:
# Chapter 1: General Introduction to machine learning (ML)
%% Cell type:markdown id: tags:
## ML = "learning models from data"
### About models
A "model" allows us to explain observations and to answer questions. For example:
1. Where will my car at given velocity stop if I apply break now?
2. Where on the night sky will I see the moon tonight?
3. Is the email I received spam?
4. Which article "X" should I recommend to a customer "Y"?
- The first two questions can be answered based on existing physical models (formulas).
- For the questions 3 and 4 it is difficult to develop explicitly formulated models.
### What is needed to apply ML ?
Problems 3 and 4 have the following in common:
- No exact model known or implementable because we have a vague understanding of the problem domain.
- But enough data with sufficient and implicit information is available.
E.g. for the spam email example:
- We have no explicit formula for such a task (and devising one would boil down to lots of trial with different statistics or scores and possibly weighting of them).
- We have a vague understanding of the problem domain because we know that some words are specific to spam emails and others are specific to my personal and work-related emails.
- My mailbox is full with examples of both spam and non-spam emails.
**In such cases machine learning offers approaches to build models based on example data.**
<divclass="alert alert-block alert-info">
<iclass="fa fa-info-circle"></i>
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.
</div>
## ML: what is "learning" ?
To create a predictive model, we must first **train** such a model on given data.
<divclass="alert alert-block alert-info">
<iclass="fa fa-info-circle"></i>
Alternative names for "to train" a model are "to <strong>fit</strong>" or "to <strong>learn</strong>" a model.
</div>
All ML algorithms have in common that they rely on internal data structures and/or parameters. Learning then builds up such data structures or adjusts parameters based on the given data. After that such models can be used to explain observations or to answer questions.
The important difference between explicit models and models learned from data:
- Explicit models usually offer exact answers to questions
- Models we learn from data usually come with inherent uncertainty.
%% Cell type:markdown id: tags:
## Some history
Some parts of ML are older than you might think. This is a rough time line with a few selected achievements from this field:
1805: Least squares regression
1812: Bayes' rule
1913: Markov Chains
1951: First neural network
1957-65: "k-means" clustering algorithm
1959: Term "machine learning" is coined by Arthur Samuel, an AI pioneer
1969: Book "Perceptrons": Limitations of Neural Networks
1995: Randomized Forests and Support Vector Machines methods
1998: Public appearance: first ML implementations of spam filtering methods; naive Bayes Classifier method
2006-12: Neural networks learning breakthrough: deep learning
So the field is not as new as one might think, but due to
- more available data
- more processing power
- development of better algorithms
more applications of machine learning appeared during the last 15 years.
%% Cell type:markdown id: tags:
## Machine learning with Python
Currently (2018) `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.
The prevalent packages in the Python eco-system used for ML include:
-`pandas` for handling tabular data
-`matplotlib` and `seaborn` for plotting
-`scikit-learn` for classical (non-deep-learning) ML
-`TensorFlow`, `PyTorch` and `Keras` for deep-learning.
`scikit-learn` is very comprehensive and the online-documentation itself provides a good introducion into ML.
%% Cell type:markdown id: tags:
## ML lingo: What are "features" ?
A typical and very common situation is that our data is presented as a table, as in the following example:
<li>The first four features have continuous numerical values within some ranges - these are called <strong>numerical features</strong>,</li>
<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>
</ul>
%% Cell type:markdown id: tags:
A straight-forward application of machine-learning on the previous beer dataset is: **"can we predict `is_yummy` from the other features"** ?
<divclass="alert alert-block alert-warning">
<iclass="fa fa-warning"></i> <strong>Even more definitions</strong>
In context of the question above we call:
<ul>
<li>the <code>alcohol_content</code>, <code>bitterness</code>, <code>darkness</code>, <code>fruitiness</code> features our <strong>input features</strong>, and</li>
<li>the <code>is_yummy</code> feature our <strong>target/output feature</strong> or a <strong>label</strong> of our data samples.
<ul>
<li>Values of categorical labels, such as <code>0</code> ("no") and <code>1</code> ("yes") here, are often called <strong>classes</strong>.</li>
</ul>
</li>
</ul>
%% Cell type:markdown id: tags:
Most of the machine learning algorithms require that every sample is represented as a vector containing numbers. Let's look now at two examples of how one can create feature vectors from data which is not naturally given as vectors:
1. Feature vectors from images
2. Feature vectors from text.
### 1st Example: How to represent images as feature vectors ?
In order to simplify our explanations we only consider grayscale images in this section.
Computers represent images as matrices. Every cell in the matrix represents one pixel, and the numerical value in the matrix cell its gray value.
So how can we represent images as vectors?
To demonstrate this we will now load a sample dataset that is included in `scikit-learn`:
:Attribute Information: 8x8 image of integer pixels in the range 0..16.
:Missing Attribute Values: None
:Creator: E. Alpaydin (alpaydin '@' boun.edu.tr)
:Date: July; 1998
This is a copy of the test set of the UCI ML hand-written digits datasets
http://archive.ics.uci.edu/ml/datas
[...]
%% Cell type:markdown id: tags:
Let's plot the first ten digits from this data set:
%% Cell type:code id: tags:
``` python
N=10
plt.figure(figsize=(2*N,5))
fori,imageinenumerate(dd.images[:N]):
plt.subplot(1,N,i+1).set_title(dd.target[i])
plt.imshow(image,cmap="gray")
```
%% Output
%% Cell type:markdown id: tags:
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.
%% Cell type:code id: tags:
``` python
print("images.ndim:",dd.images.ndim)# number of dimensions of the array
print("images[0].shape:",dd.images[0].shape)# dimensions of a first sample array
print()
print("images[0]:\n",dd.images[0])# first sample array
print("images.shape:",dd.images.shape)# dimensions of the array of all samples
print("images.size:",dd.images.size)# total number of elements of the array
print("images.dtype:",dd.images.dtype)# type of the elements in the array
print("images.itemsize:",dd.images.itemsize)# size in bytes of each element of the array
print("target.size:",dd.target.size)# size of the target feature vector (labels of samples)
### 2nd Example: How to present textual data as feature vectors?
%% Cell type:markdown id: tags:
If we start a machine learning project for texts, we first have to choose a dictionary - set of words for this project. The final representation of a text as a feature vector depends on this dictionary.
If we start a machine learning project for texts, we first have to choose a dictionary (a set of words) for this project. The words in the dictionary are enumerated. The final representation of a text as a feature vector depends on this dictionary.
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:
| Word | Index |
|----------|-------|
| like | 0 |
| dislike | 1 |
| american | 2 |
| italian | 3 |
| beer | 4 |
| pizza | 5 |
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`.
E.g. `"I dislike american pizza, but american beer is nice"`:
| Word | Index | Count |
|----------|-------|-------|
| like | 0 | 0 |
| dislike | 1 | 1 |
| american | 2 | 2 |
| italian | 3 | 0 |
| beer | 4 | 1 |
| pizza | 5 | 1 |
The respective feature vector is the `Count` column, which is:
`[0, 1, 2, 0, 1, 1]`
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 id: tags:
Below you find is a short code example to demonstrate how text feature vectors can be created with `scikit-learn`.
<divclass="alert alert-block alert-info">
<iclass="fa fa-info-circle"></i>
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., <ahref="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html">"term frequency-inverse document frequency" vectorizer</a>.
You will learn more on how to select wisely subsets of your data and about related issues later in the course. For now just remember that:
1. the training and validation datasets must be disjunct during each iteration of the method improvement, and
1. the test dataset must be independent from the model (hence, from the other datasets), i.e. it is indeed used only for the final assesment of the method's performance (think: locked in the safe until you're done with model tweaking).
%% Cell type:markdown id: tags:
## Taxonomy of machine learning
Most applications of ML belong to two categories: **supervised** and **unsupervised** learning.
### Supervised learning
In supervised learning the data comes with an additional target/label value that we want to predict. Such a problem can be either
-**classification**: we want to predict a categorical value.
-**regression**: we want to predict numbers in a given range.
Examples of supervised learning:
- Classification: predict the class `is_yummy` based on the attributes `alcohol_content`, `bitterness`, `darkness` and `fruitiness` (a standard two class problem).
- Classification: predict the digit-shown based on a 8 x 8 pixel image (a multi-class problem).
- Regression: predict temperature based on how long sun was shining in the last 10 minutes.
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:
- Clustering: find groups in data.
- Density estimation, novelty detection: find a probability distribution in your data.
- Dimension reduction (e.g. PCA): find latent structures in your data.
Examples of unsupervised learning:
- Can we split up our beer data set into sub-groups of similar beers?
- Can we reduce our data set because groups of features are somehow correlated?
<td><center>Dimension reduction: detecting 2D structure in 3D data</center></td>
</tr>
</table>
This course will only introduce concepts and methods from **supervised learning**.
%% Cell type:markdown id: tags:
## How to apply machine learning in practice?
Application of machine learning in practice consists of several phases:
1. Understand and clean your data.
1. Learn / train a model
2. Analyze model for its quality / performance
2. Apply this model to new incoming data
In practice steps 1. and 2. are iterated for different machine learning algorithms with different configurations until performance is optimal or sufficient.
%% Cell type:markdown id: tags:
# Exercise section 1
# Hands-on section
%% Cell type:markdown id: tags:
<divclass="alert alert-block alert-danger">
<strong>TODO:</strong> transform to az set of small exercises (instead of a tutorial/example as it is now).
<strong>TODO:</strong> transform to a set of small exercises (instead of a tutorial/example as it is now).
</div>
%% Cell type:markdown id: tags:
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 id: tags:
### 1. Load the data and show the overall structure using `pandas`
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.
%% Cell type:code id: tags:
``` python
importseabornassns
sns.set(style="ticks")
for_plot=beer_data.copy()
deftranslate_label(value):
# seaborn has issues if labes are numbers or strings which represent numbers,
- Points and colors don't look randomly distributed.
- We can see that some pairs like `darkness` vs `bitterness` seem to carry information which could support building a classifier.
- We also see that `bitterness` and `fruitiness` show correlation.
Features which show no structure can also decrease performance of ML and often it makes sense to discard them.
%% Cell type:markdown id: tags:
### 3. Prepare data: split features and labels
%% Cell type:code id: tags:
``` python
# all columns up to the last one:
input_features=beer_data.iloc[:,:-1]
# only the last column:
labels=beer_data.iloc[:,-1]
print('# INPUT FEATURES')
print(input_features.head(5))
print('...')
print(input_features.shape)
print()
print('# LABELS')
print(labels.head(5))
print('...')
print(labels.shape)
```
%% Output
# INPUT FEATURES
alcohol_content bitterness darkness fruitiness
0 3.739295 0.422503 0.989463 0.215791
1 4.207849 0.841668 0.928626 0.380420
2 4.709494 0.322037 5.374682 0.145231
3 4.684743 0.434315 4.072805 0.191321
4 4.148710 0.570586 1.461568 0.260218
...
(225, 4)
# LABELS
0 0
1 0
2 1
3 1
4 0
Name: is_yummy, dtype: int64
...
(225,)
%% Cell type:markdown id: tags:
### 4. Start machine learning using `scikit-learn`
%% Cell type:markdown id: tags:
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.
<divclass="alert alert-block alert-info">
<iclass="fa fa-info-circle"></i>
<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.
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).
<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.
</div>
%% Cell type:markdown id: tags:
## What happened?
Why were not all labels predicted correctly?
Neither `Python` nor `scikit-learn` is broken. What we observed above is very typical for machine-learning applications.
Reasons could be:
- we have incomplete information: other features of beer which also contribute to the rating (like "maltiness") were not measured or can not be measured.
- the used classifiers might have been not suitable for the given problem.
- noise in the data as incorrectly assigned labels also affect results.
**Finding good features is crucial for the performance of ML algorithms!**
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.
%% Cell type:markdown id: tags:
# Exercise section 2
# Exercise section 1
%% Cell type:markdown id: tags:
<divclass="alert alert-block alert-danger">
<strong>TODO:</strong> I propose to start separate excercise session 2 w/ SVC here (so if someone is stuck on previous, he/she can skip).
</div>
%% Cell type:markdown id: tags:
### 1. Compare with alternative machine learning method from `scikit-learn`
%% Cell type:markdown id: tags:
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.
<divclass="alert alert-block alert-info">
<iclass="fa fa-info-circle"></i>
<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.
</div>
%% Cell type:code id: tags:
``` python
fromsklearn.svmimportSVC
# ...
# REMOVE or HIDE the following lines in the target script
Better re-classification does not indicate here that <code>SVC</code> is better than <code>LogisticRegression</code>. At most it seems to fit better to our training data. We will learn later that this may be actually not a good thing.
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.
</div>
%% Cell type:markdown id: tags:
### 2. Experiment with (hyper)parameters of ML methods
%% Cell type:markdown id: tags:
Both `LogisticRegression` and `SVC` classifiers have a parameter `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.
**TOBE discussed**: is "regularization" to technical here ? decision surfaces and details of classifers come later. Original purpose (Uwe) was to demonstrate that classifiers can be tuned to the data set.
%% Cell type:code id: tags:
``` python
# Recall: ?LogisticRegression
# ...
```
%% Cell type:markdown id: tags:
<divclass="alert alert-block alert-danger">
<strong>TODO:</strong> prepare a solution.
</div>
%% Cell type:markdown id: tags:
# Exercise section 3 (optional)
# Exercise section 2 (optional)
%% Cell type:markdown id: tags:
<divclass="alert alert-block alert-danger">
<strong>TODO:</strong> finish solution - missing classification and "re-classification" assesment.
</div>
%% Cell type:markdown id: tags:
Load and inspect the cannonical Fisher's "Iris" data set, which is included in `scikit-learn`: see [docs for `sklearn.datasets.load_iris`](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html). What's conceptually diffferent?
Apply `LogisticRegression` or `SVC` classifiers. Is it easier or more difficult than classification of the beers data?
%% Cell type:code id: tags:
``` python
fromsklearn.datasetsimportload_iris
data=load_iris()
# labels as text
print(data.target_names)
# (rows, columns) of the feature matrix:
print(data.data.shape)
```
%% Output
['setosa' 'versicolor' 'virginica']
(150, 4)
%% Cell type:code id: tags:
``` python
# transform the scikit-learn data structure into a data frame:
/Users/mikolajr/Workspace/SSDM/machinelearning-introduction-workshop/.venv/lib/python3.7/site-packages/ipykernel_launcher.py:9: UserWarning: get_ipython_dir has moved to the IPython.paths module since IPython 4.0.
/Users/uweschmitt/Projects/machinelearning-introduction-workshop/venv3.6/lib/python3.6/site-packages/ipykernel_launcher.py:9: UserWarning: get_ipython_dir has moved to the IPython.paths module since IPython 4.0.