Docsity

Appunti di "Machine Learning", Dispense di Machine learning

Anteprima parziale del testo

Scarica Appunti di "Machine Learning" e più Dispense in PDF di Machine learning solo su Docsity!

MACHINE

LEARNING

Theoretical aspects

Vercellis A.Y. 2019- 2020

Chiara Gasparato

Politecnico di Milano

Machine Learning

What’s machine learning?

Digital disruption: new incumbent using digital technologies throws all other players out of scope

Characteristics:

  • Be based on digital platforms, allowing companies to accumulate knowledge about customers
  • They have everything; Amazon has nearly every possible book you require, Google allows you to

search for any kind of information, Spotify has not a single record, but almost everything

  • Eliminate intermediations, selling directly to the customer

Netflix started in 2003 with the main aim of beating Blockbuster with the smart idea of a subscription through

which Netflix brought your DVDs home. The only condition was not to have more than one piece at home.

Blockbuster failed and this mainly because of Netflix as new incumbent, which relied on data science (they

optimized the way to deliver the copies in the most convenient way; they were capable to predict the tastes

of customers, in order to understand how many copies they needed, optimizing the stock).

In 2006 they announced a competition of 1mln$ in which the accuracy of the algorithm was improved.

Data from Internet of People has the following characteristics:

  • Lot of data and high speed
  • They are unstructured: they do not appear as an Excel spreadsheet, they do not have neither the

same size nor a schema.

They contain texts, numbers, images, videos, sounds and they change format

Data from Internet of things has the following characteristics:

  • They are structured, based on a schema made of columns and numbers
  • Speed is very high

From data insight to data driven strategy

Big Data collection & Analysis Strategic Evaluation Metrics

  1. Data collection and integration not just from

internal information system but also from

outside sources of data

  1. Predict and optimize, find the best action,

categorize texts & images, trend analysis,

making associations and correlations

Here, the algorithm works in order to do it

  1. Analyze and discover, human-driven activity

(exploration, filter and visualize)

  1. Act & Deliver, application part

Monetization, making money out of your

data

What are the alternatives to collect and store data?

  1. Typically, there are servers based on Linux currently around 1,000 servers on one network (Cluster

commodity servers)

Pro: very cheap

Con: hard to make them work

  1. Big Data Appliance: apparently a single computer, hiding inside a network and with HADOOP as

software

Pro: key ready

Machine learning:

  1. Past Data from Data lake (all data coming from outside and inside) / Data Warehouse (data of the

company) / Data mart (data warehouse specific for a certain department)

  1. Regression : it’s a task of analysis

Tries to explain a numerical variable based on a number of explanatory variables

We have many different techniques to perform it

There’s not a better one, the winner is the one performing better in the test set

  1. Classification : the target is not numerical, instead categorical, most of the times binary

Techniques are similar to those of regression, they have lot in common

They are both called Supervised learning as they are driven by a special variable

  1. Time series analysis : can be reconducted to regression, finding the future trend based on past

Is between supervised and unsupervised

  1. Clustering : we want to build groups that should be as much similar as possible within groups and as

much different as possible between groups

  1. Associative rules

Machine learning applications (real-time):

  • Smarter healthcare
  • Multi-channel, coordinating actions towards customers
  • Trading analytics
  • Log analysis, analyzing people going to a certain website
  • Homeland security
  • Traffic control
  • Telecom, analyzing the path of people
  • Search quality
  • Manufacturing, particularly quality control
  • Fraud and risk
  • Retail, particularly sales predictions

Machine learning process

Three actors: data scientists, IT people, domain experts

  1. Data WHS: IT
  2. Objectives definition: DS and DE
  3. Data gathering and interpretation: IT

Collect data and integrate data sources

  1. Data mart: DS and IT

Extracted DB from previous data

  1. Explanatory analysis: DS

Need to check the consistency of data

  1. Attributes selection: DS

Feature engineering, data is transformed

Variables can be even changed in order to

make analysis easier

  1. Model development: DS

Run different algorithms, collect results and

choose the best one

Thousands of experiments are carried out

  1. Prediction and interpretation: DS and DE

With the interpretation we use the model to understand, not to predict

Then, prediction comes

Unsupervised

Input data:

  • Datasets, two dimensional tables where rows are the observations and columns are the data

characterizing observations

  • Attribute types:

o Categorical: binary, nominal (not having a natural ordering, e.g. province of residence) and

ordinal (having a natural ordering, e.g. education level)

o Numerical: discrete and continuous

A dataset is represented by a 𝑚 𝑥 𝑛 matrix

!"

Incomplete data , what to do?

  • Eliminate the row or the attribute after checking the reason of the absence
  • Identify missing data maybe with a special code
  • Replacement is done with numerical values, not categorical

Identify or eliminate are the best actions

Noisy data (outliers). Why do we need to identify them? Because they are the source of divergence in the

analysis

Having normal distribution, data cannot be too far away from the distribution

This depends on the level of confidence you decide to set

For instance, with 96% of the records in the interval we have superior limit as 𝜇̅ "

!

"

"

while the inferior one

will be 𝜇̅ "

!

"

"

If we don’t have a normal distribution, we can use the Chebyschev’s theorem that is always valid for any type

of distribution

Says that at least a percentage of 1 − ;

$

"

< observations fall in the interval 𝜇̅ ± 𝛾𝜎 9

Is obviously weaker than the central limit case but at least we ca identify outliers

The presence of outliers mainly depends on the dispersion, the standard deviation

Zeta-index is the standardization of the value. If the result is greater than 3, the observation is suspicious, if

much greater than 3 we have an outlier

!"

!%&

!"

"

"

However, outliers depend on the dimension we consider

It might happen that an observation is not an outlier on the x dimension nor on the y; however, generally

speaking they might look as outliers

Clustering could help in identifying the outliers, as they won’t belong to any cluster or they belong to a

cluster with little density à they are probably outliers

Data transformation

Might happen that there are different scales between variables

We need to make them more homogeneous

Standardization

Three techniques to do it:

  • Decimal scaling: scale up or down in order to have everything in the same order

!"

'

!"

(

  • Min-Max method: projection of the original segment in the final one, typically going from 0 to 1

You control in advance the variables

nd

way: Wrapper methods

Start with the subset of attribute, apply the algorithm and generate the model for those

attributes

Then, I look at all the key values of the variables that should be in module greater than 2

Backward approach, you start with all the values and you discard something going on

The stopping rule will let us keep the relevant variables

Advantage: better way of identifying relevant variables, even if not the optimal one, because we judge

after the model has been applied, a sequence of models can be considered

Disadvantage: more time consuming

Wrapping around the algorithm the cycle

rd

way: Embedded methods

Build within the algorithm the attribute selection

Trees as the easier way to do it

Example: insurance, some of the customers have life insurance, others do not

How to understand who are the most likely to be targeted to advertise the life insurance?

We have a set of attributes: [age, sex, education, income, job]

The target is life insurance=

Every observation is in the first node

Then, in each node an attribute is selected to make a split by the model

The algorithm is recursive and it continues until the target has been reached

The goal is to reach the maximum possible order, gaining a perfect split

Apart from the clusterization, the selection of the most relevant attributes has been made

In general, we have greedy search scheme:

  • Forward: start with an empty set of attributes and subsequently introduces the attributes one at a time
  • Backward: all set of attributes, eliminating them one at a time
  • Forward-backward: trade-off between the two, in which at every step the irrelevant attributes are

eliminated and the best one are included

Principal Component Analysis

Try to embed the original variables in a different space à Transformation

There are different viewpoints from which we can see things à is there a better choice of choosing the axis to

understand data?

Yes, there is a better representation with less dimensions than the original one

Replace a subset of the original numerical variable with a lower number of attributes obtained by a linear

combination without losing information

Is common to standardize the data before applying PCA, as to have all the attributes in the same range, very

likely with the interval [-1,1]

Example: 3 dimensions [income, number of subscriptions, age]

Two separations are made with parallel lines on the x and y axis

These separations could have been made through a tree

Nevertheless, there are three mistakes with this method, 3 dots belonging to the area with the opposite

colour

Performing the PCA, we find the direction of maximum variation and the second of maximum variation

Directions are a linear combination of the dimensions

Mathematically speaking, coefficients are eigen vectors of a given matrix

What if we apply classification tree to the new axis obtained by PCA?

à We obtain an improvement, the separation between blue and red is perfect now

V=X’X covariance matrix of the attributes (X transposed X)

Each element of the matrix is standardized through

Then, we want to compute the variance of the new direction

The result of the variance computation is: 𝐸 P

"

'

!

"

'

!

R

1

= ⋯ = x’ j

Vw j

If we want to maximize this result, in order to find the direction of maximum variation, we need to insert the

additional condition of w with a unique norm

The first principal component is obtained solving an optimization problem as follow (obtaining the weights):

'

'

Can be shown that the vector solving the problem is the eigenvector associated to the largest eigenvalue

The eigenvalue is equal to the amount of explained variance: 𝑣𝑎𝑟?𝑝 "

"

"

is the principal component

In the second principal component an additional condition of orthogonality with the fist will be inserted

1

'

How many principal components is it worth to be taken into account?

  1. Take the percentage of explained variance by q lambdas

2

1

2

1

%

You keep the qs until 1 is almost reached

The index explains the percentage of total variance explained by the first q principal components

  1. Scree-plot

Elbow behavior, at a certain point the plot goes down

The rule will be to take into account the components until this behavior is shown

Graphic way to choose the components

Data discretization

Reduction of the values, putting them in intervals (applicable only to numerical variables) or reduction of

number of values assumed by categorical values

The most popular discretization techniques are:

  • Subjective subdivision
  • Subdivision into classes of equal width or size
  • Hierarchical discretization for categorical variables (replace each value of an attribute with the

corresponding value at an higher level)

We move from many variables up, losing information because of the aggregation

Then we need to empirically test which is the best level

Exploratory Data Analysis

Goal: highlight relevant features of each attribute in the dataset and identify relationships among attributes

Univariate Analysis (properties of each single attribute of a dataset are investigated)
  • Categorical: we might go for a graphical or mathematical analysis

Graphical: representation of the observations through the relative frequencies with which a value

occurs

Projection of a generic x in the direction of the vector w

  • Quartiles: we have lower quartiles considering 0.25 (q L

=q

) and upper quartiles considering the

0.75 (q U

=q

The distance between quartiles gives us information about where the 50% stands:

2

8

9

Measures of central tendency based on quantiles:

  • Mid-mean: mean of the values between q L

and q U

Not sensitive to outliers, is more robust than the mean

However, too much information is taken

  • Trimmed mean: mean of the values between q

P

and q

1 - P

We lose less information

  • Windsorized mean: increase (decrease) values less (greater) then the quantile q

P

(q

1 - P

Best one to avoid losing too much information

  • Box-and-whisker

The box represents the median and lower and lower and upper quartiles

Whiskers are defined as: lower à minimum value among the observation falling in a given

interval from the lower extreme of the interval – 1.5 interquartile distance (D

q

So, we move from q L

and we cut a 1.5D q

Observations falling outside the whiskers are very suspiciously outliers

Additional way to detect outliers

Analysis of empirical density

This tool is applicable both to numerical and categorical variables

Another empirical density analysis is made by looking at the density, we can check if there’s symmetry or not

A mathematical way to assess the symmetry is the asymmetry-index

+:

;

;

𝑛 where 𝜇̅

;

_(𝑥

!

;

)

! 5 #

I

as

> 0 right asymmetry

I

as

< 0 left asymmetry

I

as

= 0 à Symmetric

Kurtosis

Expresses in a concise way the level of approximation of an empirical density to the normal curve

<=6>

?

?

− 3 where 𝜇̅

?

_(𝑥

!

?

)

! 5 #

We subtract 3 because most of the times the value is around 0

Information coming from this index will bring three different

alternatives:

  • Normal
  • Hypernormal
  • Hyponormal

Normal-probability plot

Normal distribution quantiles on the x-axis

Our distribution quantiles on the other axis

Verify if it’s reasonable to say that the distribution performs like a

normal one

Dots should be aligned to the straight line in order to be

considered a standard distribution

Bi-variate analysis

Once that univariate analysis to understand the characteristics of the dataset is carried out, it would be

appropriate to understand the relationship existing between pairs of attributes

  • Two numerical variables

Graphical Analysis

  • Scatterplot is the best way to notice if some kind of relationship is

present (first attribute aj on the horizontal axis and the second ak

on the vertical one)

Outliers are not always outliers! They can have relationships

between them

With an high number of observations, scatterplot might be really

confusing and ineffective

  • Loess diagram (Local Regression)

Comes from the Scatterplot but with a trend curve added to

express the relationship between the two attributes

The curve is coming from a local regression of the observations

Loess Diagram with 𝝺=1 and 𝝰=3/

Multivariate Analysis
  • Scatterplot matrix

We draft scatterplots for any pair formed by the categorical variables and look for some correlation

  • Star plots

Taking a circle with each ray corresponding to one numerical variable, we can represent each record

with a particular figure obtained by taking the values long each ray

Values are normalized before doing it

  • Spider web chart

Star plots that are overlapped

Classification

Most common task of application in machine learning; they are supervised learning methods for predicting

the value of a target categorical attribute

We have multi-categorical variables

Objective: obtaining a separating surface in order to separate one class from the other

The majority on one side will characterize that class

Misclassification: observations stays on the wrong class

The classification is applicable to the future, forecasting the class to which the observation will belong

Mathematical notation

)

!

!

), 𝑖 ∈ 𝑀}: 𝑡𝑟𝑎𝑖𝑛𝑖𝑛𝑔 𝑠𝑒𝑡 where 𝑥

!

are the inputs and 𝑦

!

the output for the past

ℋ 𝑑enotes a set of functions 𝑓(𝑥)

Classification problem: define a hypnotical space ℋ and a function 𝑓 which optimally describes the

relationship between x i

and y

i

With a too large space we have a risk of overfitting

Trade-off between past and future, finding an appropriate space and function

Classification problem is nothing more than reducing numerical variables into a set of binary

Multi-class approaches:

  • 1 - against-all: we take one class and the other as a combination of the two

Then, I do the same three times, thus training three models

The first one will be able to recognize one class out of the others

The second one is able to recognize another class out of the others

The third last one is able to recognize the last remaining one out of the others

Based on the values found by each model (scores) we can say with which percentage each class will

appear

Train K binary classifiers (class 1 against [2,3,…,K], class 2 against [1,3,…,K] and so on)

By applying the K trained classifiers and assigning the labels, we can predict for a new record

Adv: less effort and quicker

  • 1 - against- 1 : train K(k-1)/2 binary classifiers

I train one classifier considering one class against another, forgetting about the remaining and so on

so forth

Of course, the number of classifier is higher with respect to the 1-against-all, as we have to consider

each possible pair

Adv: higher accuracy

Taxonomy of classification methods:

  • Heuristic methods

o Classification trees

o Nearest neighbor

  • Separation methods

o Support vector machines

o Neural networks

  • Regression methods: from a binary lo a regression problem
  • Probabilistic methods

Assessing classification methods:

  • Prediction accuracy: useful to evaluate both the ability of the model to predict the target class and in

order to select the model with the best performance

  • Speed (time required to train a model)
  • Robustness (how robust are the rules generated by applying small changes in input data)
  • Scalability (ability to learn from large datasets)
  • Interpretability
  • Rules effectiveness

Development of a classification model

Separate the past data into a training set used for learning regularities and patterns and then into a test set to

validate the generated model

Empirical method, we generate many models by

using different algorithms

For each model we will check the performances and

assess the accuracy

The behavior of models is regulated by parameters

We should choose before the algorithm and then use

it on the test set

Once that the best model is chosen, it can be used to

predict the future

The scheme is applicable both on classification and

regression

Evaluation of classification models

The error in the classification problem is not a number, is a binary

!

!

!

!

The losses are the errors in classification problems

Empirical error: sum of the losses

3)A

_ 𝐿?𝑓(𝑥

!

)

! 5 #

Prediction accuracy:

  • Holdout method : split into training and test, then validating the accuracy on the test set

The observations falling in the training set are randomly chosen

Good with dataset above 50,000 records

Taking a certain percentile of the population we obtain the percentage of positives obtainable

Overfitting

The curve separating the population is too much tailored around the training set

How to interpret overfitting?

We have no error at all on the training set but what about the test set?

When the accuracy on the training set is significantly better than the one on the test set, better to discard that

model, is tailored-made on the training set

Bias-variance trade-off

This trade-off comes from the fact that we would like to have a model capable to capture the regularities in

the dataset but being capable to generalize unseen data

The error on the test set goes down up to a certain point

The higher the complexity, the higher the possibility of having overfitting (high variance) and in contrast, the

higher the bias, the lower the complexity but the lower the capability to go beyond the training set,

underfitting data

Every time there’s a categorical variable in our dataset, this should be transformed into a numerical one

Heuristic methods

K-nearest neighbor

To a new record is attributed the class to which belong the majority of records out of the K closest ones

The higher the k, the higher the robustness but unfortunately there will be less distinction among classes, less

accuracy

K is the parameter, how to select the value? à Empirical science, need to try

Best for performing predictions in time series classifications

Classification Trees

Balancing: same probability of ‘Yes’ and ‘No’

By splitting the entire dataset on the father node in pairs, the ideal situation would be to get 100% on one

side, meaning that we can obtain exact predictions

Rules are built on a numerical attribute, considering both a certain attribute and corresponding threshold

value; this is performed by the algorithm itself

The ordering is maximized (confusion is minimized)

It also maximizes the level of improvement

Then, the algorithm is applied in cascade and it stops when stopping conditions are met (most of the times is

set at 0.90 as confidence)

Going too much down the risk of overfitting comes up

The last node is still made of leaves where one leaf will contain the majority of the population. For this reason,

the prediction could be labeled as that leaf is.

The method is very easy but not as strong as others

To prevent overfitting:

  • Purity threshold:
  • Minimum cardinality
  • Minimum information gain

Post-pruning: the tree is applied on a tuning test and then verifies whether it does pay off to make the tree by

comparing the accuracy with and without the tree

Pre-pruning by stopping criteria

It might lead into an elimination of the last branches if the algorithm recognizes a sort of overfitting

Trees are distinguished in:

  • Binary trees
  • General trees: Applicable on categorical variable without

having them transformed into binary

  • Univariate trees: separate just one attribute at a time
  • Multivariate trees: more general rules. Not worth, you

lose the interpretability

Three criteria for splitting:

  • Misclassification index

(

  • Entropy index
_

(

log

1

(

4

( 5 #

  • GINI index
𝐺𝑖𝑛𝑖(𝑞) = 1 − _ 𝑝

(

1

4

( 5 #

One node called ‘q’ with 'Q’ number of records following in the node

Descendants are called q 1

, q 2

,…, q k

with

corresponding Q 1

,Q

2

,…Q

k

number of records

I (q): index of the father (either Gini or entropy or

misclassification index) and I (q 1

), I (q 2

) for the

descendants

The weighted average of the descendants will be

maximized in comparison with the father’s one,

maximizing the information gain

The curve with the angular point is the

misclassification as is computed with the

maximum, not differentiable

The most orderly situations are those on borders

The GINI index corresponds to the dotted curve

Impurity index is computed considering the population that falls in that node starting from the father

1

@

= _

@

@

D

@ 5 #

Information gain is the delta obtained between the impurity index of the father and the descendants’)

1

@

1

@

) = 𝐼(𝑞) − _

@

@

D

@ 5 #

The information gain has to be maximized or, equivalently, the impurity has to be minimized (obviously only

the descendants’ one, the father’s one is fixed)

Bayesian methods

Based on Bayes theorem

Posterior probability: 𝑃(𝑦|𝒙)

If probabilities are given, we might predict values based on the probabilities

Univariate split on categorical variables

Another critical issue is that the corresponding optimization problem is ill-posed: this means that if the space

ℱ is chosen too broad, the empirical error can be reduced a lot, but the optimal 𝑓* has low generalization

capabilities

With more complex models, there might be overfitting but with less space, it won’t overfit but may not be the

best classifier

Need to find a good trade-off between empirical error and generalization capability

How can we get to the best shape? à Need to try different alternatives

The solution proposed, known as VC dimension, was to focus on two terms: the error on past data (empirical)

and function complexity expressed as the norm

_ 𝑉?𝑦

!

!

)

! 5 #

1

D

Norm of the function: if linear, will be the norm of the coefficients

Lambda is a factor weighting the importance of complexity with respect to past errors

The VC dimension of the hypothesis space is defined as the maximum number of training points that can be

correctly classified. For instance, if VC= h, there will exists at least one set of h+1 points that cannot be

correctly classified

In the example aside, the training examples are represented by

point in a two-dimensional space with VC=3, since there exists sets

of 4 points which cannot be shattered by a single separating line.

More generally, it has been shown that the class of separating

hyperplanes in the space ℝ

n

has dimension VC= n+

Taking a high complexity space, overfitting will appear

The empirical risk goes to zero with high complexity, as having a higher space will allow us to perform better

on past errors

Sheep examples: they are all equals in terms of empirical error, they all have no error

But which one has better generalization capability? Applying a small change to one sheep, the left-oblique

line has a little generalization capability, will get an outlier, whereas the straight line won’t generate an outlier

The trajectory to take is the one with maximum distance between the line and the closest positions

As shown aside, there are infinite number of lines capable to separate the

points and all of them appear equivalent in terms of empirical error on the

training set (equal to zero in this case).

However, lines a and c, which are closer to the training examples, have

lower generalization capability with respect to line b.

Hence, the optimal separating line is the one with maximum

generalization capability and minimum empirical error, as shown in the

figure below.

We want to maximize the marginal distance, that is the distance

between points and the separating hyper-surface

We have points in the vectoral space

b is the best one, is separating with the maximum minimum distance

This is found through an optimization problem

Canonical hyperplanes: parallel planes going through the nearest

dots

Those training points which lie on the canonical hyperplanes are called support vectors and play a significant

role, since they determine precisely the classification rule.

Delta is what has to be maximized

w is the vector of coefficients of the separating hyperplane and b the intercept

then, the canonical supporting hyperplanes are:

'

𝑥 − 𝑏 − 1 = 0 and 𝑤

'

Delta is the margin of separation and is function of the coefficients:

_

"

1

In order to determine the coefficients w and b , a quadratic optimization problem can be solved

We want to minimize with respect to w and b , the norm squared

The constraint will force each point x i

to lie in the halfspace of the corresponding class value y i

The optimal solution would be all the w=0 but this is equivalent to not separating anything

à We need constraints for each point of the dataset, claiming that the point has to be on the right side of the

separating hyperplane, being on the right side (e.g. blacks on

the right and white on the left)

Above canonical hyperplane: 𝑤

'

!

Less or equal imposes to the white points to be above the

other canonical hyperplane

But what if both dots where the canonicals pass are just

outliers?

The previous problem applied to this dataset aside wouldn’t

have feasible results

We need to relax our conditions, making them weaker

How to do it? à Plug a slack

We want to minimize a weighted combination between the reciprocal of the margin of separation and the

empirical error (weight=lambda, where the value is decided based on empirical analysis)

This quadratic problem can be solved via Lagrangian duality

Lagrangian relaxation: transform a constrained optimization problem into a non-constrained problem by

moving the constraints, approximation of a difficult problem into a simpler one