
































Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!

































What’s machine learning?
Digital disruption: new incumbent using digital technologies throws all other players out of scope
Characteristics:
search for any kind of information, Spotify has not a single record, but almost everything
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:
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:
From data insight to data driven strategy
Big Data collection & Analysis Strategic Evaluation Metrics
internal information system but also from
outside sources of data
categorize texts & images, trend analysis,
making associations and correlations
Here, the algorithm works in order to do it
(exploration, filter and visualize)
Monetization, making money out of your
data
What are the alternatives to collect and store data?
commodity servers)
Pro: very cheap
Con: hard to make them work
software
Pro: key ready
Machine learning:
company) / Data mart (data warehouse specific for a certain department)
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
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
Is between supervised and unsupervised
much different as possible between groups
Machine learning applications (real-time):
Machine learning process
Three actors: data scientists, IT people, domain experts
Collect data and integrate data sources
Extracted DB from previous data
Need to check the consistency of data
Feature engineering, data is transformed
Variables can be even changed in order to
make analysis easier
Run different algorithms, collect results and
choose the best one
Thousands of experiments are carried out
With the interpretation we use the model to understand, not to predict
Then, prediction comes
Unsupervised
Input data:
characterizing observations
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?
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:
!"
'
!"
(
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:
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
"
'
!
"
'
!
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?
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
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:
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
Goal: highlight relevant features of each attribute in the dataset and identify relationships among attributes
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
=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:
and q U
Not sensitive to outliers, is more robust than the mean
However, too much information is taken
P
and q
1 - P
We lose less information
P
(q
1 - P
Best one to avoid losing too much information
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 #
as
> 0 right asymmetry
as
< 0 left asymmetry
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-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
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
Graphical Analysis
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
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/
We draft scatterplots for any pair formed by the categorical variables and look for some correlation
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
Star plots that are overlapped
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:
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
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:
o Classification trees
o Nearest neighbor
o Support vector machines
o Neural networks
Assessing classification methods:
order to select the model with the best performance
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:
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
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:
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:
having them transformed into binary
lose the interpretability
Three criteria for splitting:
(
(
log
1
(
4
( 5 #
(
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
2
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