Skip to content
Snippets Groups Projects
Commit a1e7f97a authored by schmittu's avatar schmittu :beer:
Browse files

Merge branch '27-improvements-chapter-01' into 'master'

Resolve "Improvements Chapter 01"

Closes #27

See merge request sis/courses/machinelearning-introduction-workshop!21
parents 559d8924 aad49aeb
No related branches found
No related tags found
1 merge request!21Resolve "Improvements Chapter 01"
%% Cell type:code id: tags:
``` python
# IGNORE THIS CELL WHICH CUSTOMIZES LAYOUT AND STYLING OF THE NOTEBOOK !
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import warnings
import matplotlib.pyplot as plt
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings = lambda *a, **kw: None
from IPython.core.display import HTML
HTML(open("custom.html", "r").read())
```
%% 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. What product should I recommend my customer `X` ?
- 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 ?
- We have no explicit formula for such a task.
- 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.
- We have enough example data, as my mailbox is full of both spam and non-spam emails.
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.
<div class="alert alert-block alert-info">
<i class="fa fa-info-circle"></i>
Systems with such hard coded rules are called <strong>expert systems</strong>
</div>
In such cases machine learning is a better approach.
<div class="alert alert-block alert-warning">
<i class="fa fa-info-circle"></i>
<strong>Machine learning</strong> offers approaches to automatically build predictive models based on example data.
</div>
<div class="alert alert-block alert-info">
<i class="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.
<div class="alert alert-block alert-info">
<i class="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.
<div class="alert alert-block alert-warning">
<i class="fa fa-info-circle"></i>
<strong>Learning</strong> builds up internal data structures or adjusts parameters of a ML method, based on the given data.
</div>
After ML method has learned the data, it 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, whereas
- Models that learn from data usually come with inherent uncertainty.
## Parameters / hyperparameters
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:
- *parameters* are what an ML algorithm learns from training data.
- *hyper parameters* control **how** an ML algorithm learns.
%% 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
1974-86: Neural networks learning breakthrough: backpropagation method
1984: Book "Classification And Regression Trees"
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 (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.
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:
%% Cell type:code id: tags:
``` python
import pandas as pd
features = pd.read_csv("data/beers.csv")
features.head()
```
%% Cell type:markdown id: tags:
<div class="alert alert-block alert-warning">
<i class="fa fa-warning"></i>&nbsp;<strong>Definitions</strong>
<ul>
<li>every row of such a matrix is called a <strong>sample</strong> or <strong>feature vector</strong>;</li>
<li>the cells in a row are <strong>feature values</strong>;</li>
<li>every column name is called a <strong>feature name</strong> or <strong>attribute</strong>.</li>
</ul>
Features are also commonly called <strong>variables</strong>.
</div>
%% Cell type:markdown id: tags:
This table shown holds five samples.
The feature names are `alcohol_content`, `bitterness`, `darkness`, `fruitiness` and `is_yummy`.
<div class="alert alert-block alert-warning">
<i class="fa fa-warning"></i>&nbsp;<strong>More definitions</strong>
<ul>
<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>
</div>
%% 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"** ?
<div class="alert alert-block alert-warning">
<i class="fa fa-warning"></i>&nbsp;<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>
</div>
%% Cell type:markdown id: tags:
This is how feature matrices look like in general:
<img src="images/feature_matrix.png" width=50%/>
%% 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`:
%% Cell type:code id: tags:
``` python
from sklearn.datasets import load_digits
dd = load_digits()
```
%% Cell type:code id: tags:
``` python
print(dd.DESCR)
```
%% Cell type:markdown id: tags:
Let's plot the first ten digits from this data set:
%% Cell type:code id: tags:
``` python
import matplotlib.pyplot as plt
N = 10
plt.figure(figsize=(2 * N, 5))
# dd.images: list of 8 x 8 images
# dd.target: label
for i, image in enumerate(dd.images[:N]):
plt.subplot(1, N, i + 1).set_title(dd.target[i])
plt.imshow(image, cmap="gray")
```
%% 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
dd.target
```
%% Cell type:code id: tags:
``` python
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
```
%% Cell type:markdown id: tags:
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:
%% Cell type:code id: tags:
``` python
image_vector = dd.images[0].flatten()
print("image_vector.shape:", image_vector.shape)
print("image_vector:", image_vector)
```
%% Cell type:markdown id: tags:
<br/>
This is how the final feature matrix then looks like:
<img src="images/feature_matrix_mnist.png" width=50%/>
%% Cell type:markdown id: tags:
### 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 (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.
- 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 numbered / have an index.
- 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`.
<div class="alert alert-block alert-info">
<i class="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., <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html">"term frequency-inverse document frequency" vectorizer</a>.
</div>
%% Cell type:code id: tags:
``` python
from sklearn.feature_extraction.text import CountVectorizer
vocabulary = {
"like": 0,
"dislike": 1,
"american": 2,
"italian": 3,
"beer": 4,
"pizza": 5,
}
vectorizer = CountVectorizer(vocabulary=vocabulary)
# this how one can create a count vector for a given piece of text:
vector = (
vectorizer.fit_transform(["I dislike american pizza. But american beer is nice"])
.toarray()
.flatten()
)
print(vector)
```
%% Cell type:markdown id: tags:
<br/>
The corresponding feautre matrix then has the form:
<img src="images/feature_matrix_document.png" width=70% />
%% Cell type:markdown id: tags:
## One hot encoding
The so called **one-hot-encoding** is a method to encode categorial features.
Let's assume our beer data set has an extra column to encode the beer style:
%% Cell type:code id: tags:
``` python
pd.read_csv("data/beers_with_style.csv").head()
```
%% Output
alcohol_content bitterness darkness fruitiness style is_yummy
0 3.739295 0.422503 0.989463 0.215791 pilsener 0
1 4.207849 0.841668 0.928626 0.380420 ale 0
2 4.709494 0.322037 5.374682 0.145231 stout 1
3 4.684743 0.434315 4.072805 0.191321 pilsener 1
4 4.148710 0.570586 1.461568 0.260218 ale 0
%% Cell type:markdown id: tags:
The style column can take three different values: `pilsener`, `ale` and `stout`.
To apply *one-hot-encoding* we replace the column `style` by three new columns `is_pilsener`, `is_ale` and `is_stout`:
%% Cell type:code id: tags:
``` python
pd.read_csv("data/beers_with_one_hot_encoding.csv").head()
```
%% Output
alcohol_content bitterness darkness fruitiness is_ale is_pilsener \
0 3.739295 0.422503 0.989463 0.215791 0 1
1 4.207849 0.841668 0.928626 0.380420 1 0
2 4.709494 0.322037 5.374682 0.145231 0 0
3 4.684743 0.434315 4.072805 0.191321 0 1
4 4.148710 0.570586 1.461568 0.260218 1 0
is_stout is_yummy
0 0 0
1 0 0
2 1 1
3 0 1
4 0 0
%% Cell type:markdown id: tags:
As you can see
- the new columns only have values `0` or `1`
- for each row exactly one entry of `is_pilsener`, `is_ale` and `is_stout` is `1`, all others are `0`.
%% Cell type:markdown id: tags:
<div class="alert alert-block alert-info">
<i class="fa fa-info-circle"></i>
We will later see that <code>scikit-learn</code> has functions to transform categorical data into an appropriate one-hot-encoding.
</div>
%% 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.
<table>
<tr>
<td><img src="./images/classification-svc-2d-poly.png" width=400px></td>
<td><img src="./images/regression-lin-1d.png" width=400px></td>
</tr>
<tr>
<td><center>Classification</center></td>
<td><center>Linear regression</center></td>
</tr>
</table>
%% Cell type:markdown id: tags:
### Unsupervised learning
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?
<table>
<tr>
<td><img src="./images/cluster-image.png/" width=400px></td>
<td><img src="./images/nonlin-pca.png/" width=400px></td>
</tr>
<tr>
<td><center>Clustering</center></td>
<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.
<div class="alert alert-block alert-warning">
<i class="fa fa-warning"></i>&nbsp;<strong>Garbage in / garbage out</strong>
The principle of "garbage in, garbage out" also applies in machine learning.
Cleaning data to remove strong outliers or erroneous entries is crucial in real-world problems and can be the most time-consuming part.
</div>
%% Cell type:markdown id: tags:
# Hands-on section
<img src="./images/303yin.jpg" width=35%/>
%% 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:
### Step 1: Load the data and show the overall structure using `pandas`
%% Cell type:code id: tags:
``` python
import pandas as pd
# read some data
beer_data = pd.read_csv("data/beers.csv")
print(beer_data.shape)
```
%% Cell type:code id: tags:
``` python
# show first 5 rows
beer_data.head()
```
%% Cell type:code id: tags:
``` python
# show basic statistics of the data
beer_data.describe()
```
%% Cell type:markdown id: tags:
### Step 2: Visualy inspect data using `seaborn`
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
import seaborn as sns
sns.set(style="ticks")
for_plot = beer_data.copy()
def translate_label(value):
# seaborn has issues if labes are numbers or strings which represent numbers,
# for whatever reason "real" text labels work
return "no" if value == 0 else "yes"
for_plot["is_yummy"] = for_plot["is_yummy"].apply(translate_label)
sns.pairplot(for_plot, hue="is_yummy", diag_kind="hist", diag_kws=dict(alpha=0.5));
```
%% Cell type:markdown id: tags:
What do we see?
- 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.
- We see slightly different distributions for features for each class.
Features which show no structure can also decrease performance of ML and often it makes sense to discard them.
%% Cell type:markdown id: tags:
### Step 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)
```
%% Cell type:markdown id: tags:
### Step 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.
<div class="alert alert-block alert-info">
<i class="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.
</div>
%% Cell type:code id: tags:
``` python
from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression()
classifier
```
%% Cell type:markdown id: tags:
<div class="alert alert-block alert-warning">
<i class="fa fa-warning"></i>&nbsp;<strong>Built-in documentation</strong>
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).
</div>
%% Cell type:markdown id: tags:
<div class="alert alert-block alert-warning">
<i class="fa fa-warning"></i>&nbsp;<strong><code>scikit-learn</code> API</strong>
In <code>scikit-learn</code> all classifiers have:
<ul>
<li>a <strong><code>fit()</code></strong> method to learn from data, and</li>
<li>and a subsequent <strong><code>predict()</code></strong> method for predicting classes from input features.</li>
</ul>
</div>
%% Cell type:code id: tags:
``` python
# Sanity check: can't predict if not fitted (trained)
classifier.predict(input_features)
```
%% Cell type:code id: tags:
``` python
# Fit
classifier.fit(input_features, labels)
# Predict
predicted_labels = classifier.predict(input_features)
print(predicted_labels.shape)
```
%% Cell type:markdown id: tags:
Here we've just re-classified our training data. Lets check our result with a few examples:
%% Cell type:code id: tags:
``` python
for i in range(3):
print(labels[i], "predicted as", predicted_labels[i])
```
%% Cell type:markdown id: tags:
What, "0 predicted as 1"? This looks suspicious!
Lets investigate this further:
%% Cell type:code id: tags:
``` python
print(len(labels), "examples")
print(sum(predicted_labels == labels), "labeled correctly")
```
%% Cell type:markdown id: tags:
<div class="alert alert-block alert-info">
<i class="fa fa-info-circle"></i>
<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:
<div style="font-weight: bold; font-size: 200%;">What happened?</div>
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 sufficient features and clean data 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
%% Cell type:markdown id: tags:
### 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.
<div class="alert alert-block alert-info">
<i class="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
from sklearn.svm import SVC
classifier = SVC()
# ...
```
%% Cell type:code id: tags:solution
``` python
classifier = SVC()
classifier.fit(input_features, labels)
predicted_labels = classifier.predict(input_features)
assert predicted_labels.shape == labels.shape
print(len(labels), "examples")
print(sum(predicted_labels == labels), "labeled correctly")
```
%% Cell type:markdown id: tags:
Better?
<div class="alert alert-block alert-info">
<i class="fa fa-info-circle"></i>
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:
### Experiment with hyperparameters of ML methods
%% Cell type:markdown id: tags:
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.
%% Cell type:code id: tags:
``` python
# Recall: ?LogisticRegression
# ...
```
%% Cell type:code id: tags:solution
``` python
from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression(C=2)
classifier.fit(input_features, labels)
predicted_labels = classifier.predict(input_features)
assert predicted_labels.shape == labels.shape
print(len(labels), "examples")
print(sum(predicted_labels == labels), "labeled correctly")
print(sum(predicted_labels == labels) / len(labels) * 100, "% labeled correctly")
```
%% Cell type:markdown id: tags:
<div class="alert alert-block alert-warning">
<i class="fa fa-warning"></i>&nbsp;<strong>Classifiers have hyper-parameters</strong>
All classifiers have hyper-parameters, e.g. the `C` we have seen before. It is an incident that both, `LogisticRegression` and `SVC`, have parameter named `C`. Beyond that some classifiers have more than one parameter, e.g. `SVC` also has a parameter `gamma`. But more about these details later.
</div>
%% Cell type:markdown id: tags:
## Optional exercise
%% 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?
Inspect the data using scatter plots.
Apply `LogisticRegression` or `SVC` classifiers. Is it easier or more difficult than classification of the beers data?
%% Cell type:code id: tags:
``` python
from sklearn.datasets import load_iris
data = load_iris()
# labels as text
print(data.target_names)
# (rows, columns) of the feature matrix:
print(data.data.shape)
```
%% Cell type:code id: tags:
``` python
# transform the scikit-learn data structure into a data frame:
df = pd.DataFrame(data.data, columns=data.feature_names)
# add new column
df["class"] = data.target
df.head()
```
%% Cell type:code id: tags:
``` python
# SOLUTION STARTS HERE
```
%% Cell type:code id: tags:solution
``` python
import seaborn as sns
sns.set(style="ticks")
for_plot = df.copy()
def transform_label(class_):
return data.target_names[class_]
# seaborn does not work here if we use numeric values in the class
# column, or strings which represent numbers. To fix this we
# create textual class labels
for_plot["class"] = for_plot["class"].apply(transform_label)
sns.pairplot(for_plot, hue="class", diag_kind="hist");
```
%% Cell type:code id: tags:solution
``` python
features = df.iloc[:, :-1]
labels = df.iloc[:, -1]
# classifier = SVC()
classifier = LogisticRegression(max_iter=200)
classifier.fit(features, labels)
predicted_labels = classifier.predict(features)
assert predicted_labels.shape == labels.shape
print(len(labels), "examples")
print(sum(predicted_labels == labels), "labeled correctly")
```
%% Cell type:markdown id: tags:
Copyright (C) 2019-2021 ETH Zurich, SIS ID
......
images/activate_cell_meta.png

75.4 KiB

images/feature_matrix.png

51.6 KiB

File added
images/feature_matrix_document.png

47.5 KiB

File added
images/feature_matrix_mnist.png

47.5 KiB

File added
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment