Datascience Notes
Datascience Notes
Introduction to Data
Science
ELiteTech Intern
UNIT-1
Introduction, Toolboxes: Python, fundamental libraries for data Scientists.
Integrated development environment (IDE). Data operations: Reading, selecting,
filtering, manipulating, sorting, grouping, rearranging, ranking, and plotting.
UNIT-2
Descriptive statistics, data preparation. Exploratory Data Analysis data
summarization, data distribution, measuring asymmetry. Sample and estimated
mean, variance and standard score. Statistical Inference frequency approach,
variability of estimates, hypothesis testing using confidence intervals, using p-
values
UNIT-3
Supervised Learning: First step, learning curves, training-validation and test.
Learning models generalities, support vector machines, random forest. Examples
UNIT-4
Regression analysis, Regression: linear regression simple linear regression,
multiple & Polynomial regression, Sparse model. Unsupervised learning,
clustering, similarity and distances, quality measures of clustering, case study.
UNIT-5
Network Analysis, Graphs, Social Networks, centrality, drawing centrality of
Graphs, PageRank, Ego-Networks, community Detection
TEXT/REFERENCES BOOK:
1. Introduction to Data Science a Python approach to concepts, Techniques and
Applications, Igual, L;Seghi’, S. Springer, ISBN:978-3-319-50016-4
2. Data Analysis with Python A Modern Approach, David Taieb, Packt Publishing,
ISBN-9781789950069
3. Python Data Analysis, Second Ed., Armando Fandango, Packt Publishing, ISBN:
9781787127487
COURSE OUTCOMES:
1. Describe what Data Science is and the skill sets needed to be a data scientist
2. Explain the significance of exploratory data analysis (EDA) in data science
3. Ability to learn the supervised learning, SVM
4. Apply basic machine learning algorithms (Linear Regression)
5. Explore the Networks, PageRank
UNIT NO TOPIC PAGE NO
Introduction
Introduction, Toolboxes: Python, fundamental
libraries for data Scientists. 5-10
I
Integrated development environment 10-16
(IDE).
Data Operations
17-29
Descriptive statistics, data
preparation
Descriptive statistics 30-33
II Exploratory Data Analysis data 33-49
summarization
Statistical Inference frequency 50-60
approach
Supervised Learning
III
Supervised Learning 61-75
Learning models generalities, 76-95
support vector machines
IV Regression analysis
Regression analysis,
You have, no doubt, already experienced data science in several forms. When
you are looking for information on the web by using a search engine or asking
your mobile phone for directions, you are interacting with data science
products. Data science has been behind resolving some of our most common
daily tasks for several years.
Most of the scientific methods that power data science are not new and
they havebeen out there, waiting for applications to be developed, for a long
time. Statistics is an old science that stands on the shoulders of eighteenth-
century giants such as Pierre Simon Laplace (1749–1827) and Thomas Bayes
(1701–1761). Machine learning isyounger, but it has already moved beyond
its infancy and can be considered a well- established discipline. Computer
science changed our lives several decades ago andcontinues to do so; but it
cannot be considered new.
So, why is data science seen as a novel trend within business reviews, in
technologyblogs, and at academic conferences?
The novelty of data science is not rooted in the latest scientific knowledge,
but in a disruptive change in our society that has been caused by the evolution of
technology: datification. Datification is the process of rendering into data aspects
of the world that have never been quantified before. At the personal level, the
list of datified conceptsis very long and still growing: business networks, the
lists of books we are reading,the films we enjoy, the food we eat, our physical
activity, our purchases, our drivingbehavior, and so on. Even our thoughts are
datified when we publish them on our favorite social network; and in a not so
distant future, your gaze could be datified by wearable vision registering
devices. At the business level, companies are datifying semi-structured data
that were previously discarded: web activity logs, computer network activity,
machinery signals, etc. Nonstructured data, such as written reports,e-mails, or
voice recordings, are now being stored not only for archive purposes butalso
to be analyzed.
However, datification is not the only ingredient of the data science revolution. The
other ingredient is the democratization of data analysis. Large companies such as
Google, Yahoo, IBM, or SAS were the only players in this field when data science
had no name. At the beginning of the century, the huge computational resources
of those companies allowed them to take advantage of datification by using
analytical techniques to develop innovative products and even to take decisions
about their own business. Today, the analytical gap between those companies
and the rest of the world (companies and people) is shrinking. Access to cloud
computing allows any individual to analyze huge amounts of data in short periods
of time. Analyticalknowledge is free and most of the crucial algorithms that are
needed to create a solution can be found, because open-source development is the
norm in this field. As a result, the possibility of using rich data to take evidence-
based decisions is open to virtually any person or company.
Data science is commonly defined as a methodology by which actionable insights
can be inferred from data. This is a subtle but important difference with respect
to previous approaches to data analysis, such as business intelligence or
exploratory statistics. Performing data science is a task with an ambitious
objective: the produc-tion of beliefs informed by data and to be used as the basis
of decision-making. In the absence of data, beliefs are uninformed and decisions,
in the best of cases, are based on best practices or intuition. The representation of
complex environments by rich data opens up the possibility of applying all the
scientific knowledge we have regarding how to infer knowledge from data.
In general, data science allows us to adopt four different strategies to explore
theworld using data:
planned for retail store staff during the following week, by analyzing data
suchas weather, historic sales, traffic conditions, etc.
4. Understanding people and the world. This is an objective that at the
moment is beyond the scope of most companies and people, but large
companies and governments are investing considerable amounts of money in
research areas such as understanding natural language, computer vision,
psychology and neu- roscience. Scientific understanding of these areas is
important for data science because in the end, in order to take optimal
decisions, it is necessary to know the real processes that drive people’s
decisions and behavior. The development of deep learning methods for
natural language understanding and for visual object recognition is a good
example of this kind of research.
Introduction
In this chapter, first we introduce some of the tools that data scientists use. The
toolbox of any data scientist, as for any kind of programmer, is an essential
ingredient for success and enhanced performance. Choosing the right tools can
save a lot of time and thereby allow us to focus on data analysis.
The most basic tool to decide on is which programming language we will use.
Many people use only one programming language in their entire life: the first and
only one they learn. For many, learning a new language is an enormous task that,
if at all possible, should be undertaken only once. The problem is that some
languages are intended for developing high-performance or production code,
such as C, C++, or Java, while others are more focused on prototyping code,
among these the best known are the so-called scripting languages: Ruby, Perl, and
Python. So, depending on the first language you learned, certain tasks will, at the
very least, be rather tedious. The main problem of being stuck with a single
language is that many basic tools simply will not be available in it, and eventually
you will have either to reimplementthem or to create a bridge to use some other
language just for a specific task.
In conclusion, you either have to be ready to change to the best language for
each task and then glue the results together, or choose a very flexible language
with a rich ecosystem (e.g., third-party open-source libraries). In this book we
have selected Python as the programming language.
Why Python?
Python1 is a mature programming language but it also has excellent properties
for newbie programmers, making it ideal for people who have never programmed
before. Some of the most remarkable of those properties are easy to read code,
suppression of non-mandatory delimiters, dynamic typing, and dynamic memory
usage. Pythonis an interpreted language, so the code is executed immediately in
the Python con- sole without needing the compilation step to machine language.
Besides the Python console (which comes included with any Python installation)
you can find other in-teractive consoles, such as IPython,2 which give you a richer
environment in whichto execute your Python code.
Currently, Python is one of the most flexible programming languages. One of
its main characteristics that makes it so flexible is that it can be seen as a
multiparadigm language. This is especially useful for people who already know how
to program with other languages, as they can rapidly start programming with Python
in the same way. For example, Java programmers will feel comfortable using
Python as it supports the object-oriented paradigm, or C programmers could mix
Python and C code using cython. Furthermore, for anyone who is used to
programming in functional languages such as Haskell or Lisp, Python also has basic
statements for functional programming in its own core library.
In this book, we have decided to use Python language because, as explained
before, it is a mature language programming, easy for the newbies, and can be
used as a specific platform for data scientists, thanks to its large ecosystem of
scientific libraries and its high and vibrant community. Other popular alternatives
to Python for data scientists are R and MATLAB/Octave.
The Python community is one of the most active programming communities with
ahuge number of developed toolboxes. The most popular Python toolboxes for
any data scientist are NumPy, SciPy, Pandas, and Scikit-Learn.
NumPy3 is the cornerstone toolbox for scientific computing with Python. NumPy
provides, among other things, support for multidimensional arrays with basic
oper-ations on them and useful linear algebra functions. Many toolboxes use the
NumPyarray representations as an efficient basic data structure. Meanwhile, SciPy
provides a collection of numerical algorithms and domain-specific toolboxes,
including signal processing, optimization, statistics, and much more. Another core
toolbox in SciPyis the plotting library Matplotlib. This toolbox has many tools for
data visualization.
SCIKIT-Learn: Machine Learning in Python
Scikit-learn4 is a machine learning library built from NumPy, SciPy, and Matplotlib.
Scikit-learn offers simple and efficient tools for common tasks in data analysis such
as classification, regression, clustering, dimensionality reduction, model
selection, and preprocessing.
Pandas5 provides high-performance data structures and data analysis tools. The
keyfeature of Pandas is a fast and efficient DataFrame object for data manipulation
withintegrated indexing. The DataFrame structure can be seen as a spreadsheet
which offers very flexible ways of working with it. You can easily transform any
dataset in the way you want, by reshaping it and adding or removing columns or
rows. It also provides high-performance functions for aggregating, merging, and
joining dataset-
s. Pandas also has tools for importing and exporting data from different formats:
comma-separated value (CSV), text files, Microsoft Excel, SQL databases, and the
fast HDF5 format. In many situations, the data you have in such formats will not
be complete or totally structured. For such cases, Pandas offers handling of miss-
ing data and intelligent data alignment. Furthermore, Pandas provides a
convenientMatplotlib interface.
Before we can get started on solving our own data-oriented problems, we will need
toset up our programming environment. The first question we need to answer
concerns
Python language itself. There are currently two different versions of Python: Python
2.X and Python 3.X. The differences between the versions are important, so there
isno compatibility between the codes, i.e., code written in Python 2.X does not
workin Python 3.X and vice versa. Python 3.X was introduced in late 2008; by then,
a lotof code and many toolboxes were already deployed using Python 2.X (Python
2.0 was initially introduced in 2000). Therefore, much of the scientific community
didnot change to Python 3.0 immediately and they were stuck with Python 2.7. By
now, almost all libraries have been ported to Python 3.0; but Python 2.7 is sti ll
maintained, so one or another version can be chosen. However, those who
already have a large amount of code in 2.X rarely change to Python 3.X. In our
examples throughout thisbook we will use Python 2.7.
Once we have chosen one of the Python versions, the next thing to decide is
whether we want to install the data scientist Python ecosystem by individual
tool- boxes, or to perform a bundle installation with all the needed toolboxes
(and a lot more). For newbies, the second option is recommended. If the first
option is chosen,then it is only necessary to install all the mentioned toolboxes in the
previous section, in exactly that order.
However, if a bundle installation is chosen, the Anaconda Python
distribution6 is then a good option. The Anaconda distribution provides
integration of all the Python toolboxes and applications needed for data
scientists into a single directory without mixing it with other Python toolboxes
installed on the machine. It contain- s, of course, the core toolboxes and
applications such as NumPy, Pandas, SciPy, Matplotlib, Scikit-learn, IPython,
Spyder, etc., but also more specific tools for other related tasks such as data
visualization, code optimization, and big data processing.
For any programmer, and by extension, for any data scientist, the integrated de-
velopment environment (IDE) is an essential tool. IDEs are designed to maximize
programmer productivity. Thus, over the years this software has evolved in order
tomake the coding task less complicated. Choosing the right IDE for each person
is crucial and, unfortunately, there is no “one-size-fits-all” programming
environment. The best solution is to try the most popular IDEs among the
community and keep whichever fits better in each case.
In general, the basic pieces of any IDE are three: the editor, the compiler, (or
interpreter) and the debugger. Some IDEs can be used in multiple programming
languages, provided by language-specific plugins, such as Netbeans7 or Eclipse.8
Others are only specific for one language or even a specific programming task. In
the case of Python, there are a large number of specific IDEs, both commercial
(PyCharm,9 WingIDE10 …) and open-source. The open-source community helps
IDEs to spring up, thus anyone can customize their own environment and share it
with the rest of the community. For example, Spyder 11 (Scientific Python
Development EnviRonment) is an IDE customized with the task of the data
scientist in mind.
With the advent of web applications, a new generation of IDEs for interactive lan-
guages such as Python has been developed. Starting in the academia and e-
learningcommunities, web-based IDEs were developed considering how not only
your codebut also all your environment and executions can be stored in a server.
One of the first applications of this kind of WIDE was developed by William Stein in
early 2005 using Python 2.3 as part of his SageMath mathematical software. In
SageMath, a server can be set up in a center, such as a university or school, and
then students can work on their homework either in the classroom or at home,
starting from exactly the same point they left off. Moreover, students can execute
all the previous steps overand over again, and then change some particular code
cell (a segment of the docu- ment that may content source code that can be
executed) and execute the operation again. Teachers can also have access to
student sessions and review the progress orresults of their pupils.
Nowadays, such sessions are called notebooks and they are not only used in
classrooms but also used to show results in presentations or on business
dashboards. The recent spread of such notebooks is mainly due to IPython. Since
December 2011, IPython has been issued as a browser version of its interactive
console, called IPython notebook, which shows the Python execution results very
clearly and concisely by means of cells. Cells can contain content other than code.
For example, markdown (a wiki text language) cells can be added to introduce
algorithms. It is also possible toinsert Matplotlib graphics to illustrate examples or
even web pages. Recently, some scientific journals have started to accept
notebooks in order to show experimental results, complete with their code and
data sources. In this way, experiments can become completely and absolutely
replicable.
Since the project has grown so much, IPython notebook has been separated
fromIPython software and now it has become a part of a larger project: Jupyter12.
Jupyter (for Julia, Python and R) aims to reuse the same WIDE for all these
interpreted languages and not just Python. All old IPython notebooks are
automatically imported to the new version when they are opened with the
Jupyter platform; but once they
Throughout this book, we will come across many practical examples. In this chapter,
we will see a very basic example to help get started with a data science
ecosystem from scratch. To execute our examples, we will use Jupyter notebook,
although anyother console or IDE can be used.
Fig. 2.1 IPython notebook home page, displaying a home tree directory
To execute just one cell, we press the ¸ button or click on Cell Run or press
the keys Ctrl + Enter . While execution is underway, the header of the cell shows the
* mark:
In[*]: import pandas as pd
import numpy as np
import m a t p l o t l i b . p y p l o t as plt
12 2 Toolboxes for Data Scientists
While a cell is being executed, no other cell can be executed. If you try to
executeanother cell, its execution will not start until the first cell has finished its
execution.Once the execution is finished, the header of the cell will be replaced
by the next number of execution. Since this will be the first cell executed, the
number shown will
be 1. If the process of importing the libraries is correct, no output cell is produced.
In[1]:
import pandas as pd
import numpy as np
import m a t p l o t l i b . p y p l o t as plt
For simplicity, other chapters in this book will avoid writing these imports.
In this example, we use the pandas DataFrame object constructor with a dictionary
of lists as argument. The value of each entry in the dictionary is the name of the
column, and the lists are their values.
The DataFrame columns can be arranged at construction time by entering a
key-word columnswith a list of the names of the columns ordered as we want. If
the
Get Started
with Python for Data Scientists 13
column keyword is not present in the constructor, the columns will be arranged
in alphabetical order. Now, if we execute this cell, the result will be a table like
Out[2]: this:
where each entry in the dictionary is a column. The index of each row is created
automatically taking the position of its elements inside the entry lists, starting from 0.
Although it is very easy to create DataFrames from scratch, most of the time
what we will need to do is import chunks of data into a DataFrame structure, and
we willsee how to do this in later examples.
Apart from DataFrame data structure creation, Panda offers a lot of
functions to manipulate them. Among other things, it offers us functions for
aggregation, manipulation, and transformation of the data. In the following
sections, we will introduce some of these functions.
Reading
Let us start reading the data we downloaded. First of all, we have to create a new
notebook called Open Government Data Analysis and open it. Then, after ensuring
that the educ_figdp_1_Data.csvfile is stored in the same directoryas our notebook
directory, we will write the following code to read and show the content:
Out[1]:
TIME GEO Value
0 2000 European Union ... NaN
1 2001 European Union ... NaN
2 2002 European Union ... 5.00
3 2003 European Union ... 5.03
... ... ... ...
382 2010 Finland 6.85
383 2011 Finland 6.76
384 rows × 5 columns
The way to read CSV (or any other separated value, providing the separator
character) files in Pandas is by calling the read_csvmethod. Besides the nameof
the file, we add the na_values key argument to this method along with the character
that represents “non available data” in the file. Normally, CSV files have aheader
with the names of the columns. If this is the case, we can use the usecols
parameter to select which columns in the file will be used.
In this case, the DataFrame resulting from reading our data is stored in edu. The
output of the execution shows that the edu DataFrame size is 384 r o w×s 3 columns.
Since the DataFrame is too large to be fully displayed, three dots appear in the middle
of each row.
Beside this, Pandas also has functions for reading files with formats such as Excel,
HDF5, tabulated files, or even the content from the clipboard (read_excel(),
read_hdf(), read_table(), read_clipboard()). Whichever function we use, the
result of reading a file is stored as a DataFrame structure.
To see how the data looks, we can use the head() method, which shows just the
first five rows. If we use a number as an argument to this method, this will be the
number of rows that will be listed:
.
2.6 Get Started with Python for Data Scientists 15
In [2]:
Similarly, it exists the tail()method, which returns the last five rows by default.
In [3]:
If we want to know the names of the columns or the names of the indexes, we
can use the DataFrame attributes columns and index respectively. The names of the
columns or indexes can be changed by assigning a new list of the same length to
these attributes. The values of any DataFrame can be retrieved as a Python array
bycalling its valuesattribute.
If we just want quick statistical information on all the numeric columns in a
DataFrame, we can use the function describe(). The result shows the count, the
mean, the standard deviation, the minimum and maximum, and the percentiles,
by default, the 25th, 50th, and 75th, for all the values in each column or series.
Selecting Data
In[5]:
Out[5]: 0 NaN
1 NaN
2 5.00
3 5.03
4 4.95
. ..... 3806.10
381 6.81
382 6.85
383 6.76
Name: Value, dtype: float64
If we want to select a subset of rows from a DataFrame, we can do so by indicating
a range of rows separated by a colon (:) inside the square brackets. This is commonly
known as a slice of rows:
In [6]: edu [10:14]
This instruction returns the slice of rows from the 10th to the 13th position.
Notethat the slice does not use the index labels as references, but the position. In
this case, the labels of the rows simply coincide with the position of the rows.
If we want to select a subset of columns and rows using the labels as our
references instead of the positions, we can use ixindexing:
In[7]:
2.6 Get Started with Python for Data Scientists 17
This returns all the rows between the indexes specified in the slice before the
comma, and the columns specified as a list after the comma. In this case, ixreferences
the index labels, which means that ix does not return the 90th to 94th rows, but it
returns all the rows between the row labeled 90 and the row labeled 94; thus if
the index 100 is placed between the rows labeled as 90 and 94, this row would
also bereturned.
Filtering Data
Another way to select a subset of data is by applying Boolean indexing. This indexing
is commonly known as a filter. For instance, if we want to filter those values less
than or equal to 6.5, we can do it like this:
In [8]:
Boolean indexing uses the result of a Boolean operation over the data,
returninga mask with True or False for each row. The rows marked True in the
mask will be selected. In the previous example, the Boolean operation
edu[’Value’] >produces a Boolean mask. When an element in the “Value” column
is greaterthan 6.5, the corresponding value in the mask is set to True, otherwise
it is set to False. Then, when this mask is applied as an index in edu[edu[’Value’] >
6.5], the result is a filtered DataFrame containing only rows with values higher
than 6.5. Of course, any of the usual Boolean operators can be used for filtering:
<(less than),<= (less than or equal to), > (greater than), >= (greater than or equal
to), = (equal to), and != (not equal to).
Pandasuses the special value NaN(not a number) to represent missing values. InPython, NaNis
18 2 Toolboxes for Data Scientists
one of their results ends in an undefined value. A subtle feature of NaN values is that
two NaN are never equal. Because of this, the only safe way to tell whether a value is
missing in a DataFrame is by using the isnull() function. Indeed, this function can be
used to filter rows with missing values:
In[9]:
Manipulating Data
Once we know how to select the desired data, the next thing we need to know is
howto manipulate data. One of the most straightforward things we can do is to
operate with columns or rows using aggregation functions. Table 2.1 shows a list of
the most common aggregation functions. The result of all these functions applied
to a row or column is always a number. Meanwhile, if a function is applied to a
DataFrame or aselection of rows and columns, then you can specify if the function
should be appliedto the rows for each column (setting the axis=0keyword on the
invocation of thefunction), or it should be applied on the columns for each row
(setting the axis=1keyword on the invocation of the function).
edu . m ax ( a x is = 0)
In [10]:
2.6 Get Started with Python for Data Scientists 19
Out[10]:TIME 2011
GEO Spain
Value 8.81
dtype: object
Note that these are functions specific to Pandas, not the generic Python
functions. There are differences in their implementation. In Python, NaN values
propagate through all operations without raising an exception. In contrast,
Pandas operations exclude NaNvalues representing missing data. For example, the
pandas maxfunctionexcludes NaN values, thus they are interpreted as missing values,
while the standard Python max function will take the mathematical interpretation of
NaN and return it as the maximum:
In [11]: print " Pandas max function :" , edu [ ’ Value ’]. max ()
print " Python max function :" , max ( edu [ ’ Value ’])
Out[12]: 0 NaN
1 NaN
2 0.0500
3 0.0503
4 0.0495
Name: Value, dtype: float64
However, we can apply any function to a DataFrame or Series just setting its name
as argument of the applymethod. For example, in the following code, we apply
the sqrtfunction from the NumPy library to perform the square root of each value
in the Valuecolumn.
In [13]:
Out[13]: 0 NaN
1 NaN
2 2.236068
3 2.242766
4 2.224860
Name: Value, dtype: float64
20 2 Toolboxes for Data Scientists
If we need to design a specific function to apply it, we can write an in-line function,
commonly known as a λ-function. A λ-function is a function without a name. It is
only necessary to specify the parameters it receives, between the lambda keyword
and the colon (:). In the next example, only one parameter is needed, which will
bethe value of each element in the Value column. The value the function returns will
be the square of that value.
In [14]:
s = edu [" Value " ]. apply ( l a m b d a d: d * * 2)
s. head ()
Out[14]: 0 NaN
1 NaN
2 25.0000
3 25.3009
4 24.5025
Name: Value, dtype: float64
Another basic manipulation operation is to set new values in our DataFrame. This
can be done directly using the assign operator (=) over a DataFrame. For example, to
add a new column to a DataFrame, we can assign a Series to a selection of a
column that does not exist. This will produce a new column in the DataFrame
after all the others. You must be aware that if a column with the same name
already exists, the previous values will be overwritten. In the following example,
we assign the Series that results from dividing the Value column by the maximum
value in the same column to a new column named ValueNorm.
In [15]: edu [ ’ ValueNorm ’] = edu [ ’ Value ’]/ edu [ ’ Value ’]. max ()
edu . tail ()
Now, if we want to remove this column from the DataFrame, we can use the drop
function; this removes the indicated rows if axis=0, or the indicated columns if
axis=1. In Pandas, all the functions that change the contents of a DataFrame, such
as the drop function, will normally return a copy of the modified data, instead of
overwriting the DataFrame. Therefore, the original DataFrame is kept. If you do
notwant to keep the old values, you can set the keyword inplaceto True. By default,
this keyword is set to False, meaning that a copy of the data is returned.
Finally, if we want to remove this row, we need to use the drop function again.
Now we have to set the axis to 0, and specify the index of the row we want to
remove. Since we want to remove the last row, we can use the max function over
the indexesto determine which row is.
In [18]: edu . drop ( max ( edu . index ) , axis = 0 , inplace = True )
edu . tail ()
In [19]: eduDrop = edu . drop ( edu [" Value " ]. isnull () , axis = 0)
eduDrop . head ()
22 2 Toolboxes for Data Scientists
To remove NaN values, instead of the generic drop function, we can use the
specificdropna() function. If we want to erase any row that contains an NaN value, we
have to set the how keyword to any. To restrict it to a subset of columns, we can
specify it using the subset keyword. As we can see below, the result will be the same
as using the dropfunction:
In [20]:
eduDrop = edu . dropna ( how = ’ any ’, subset = [" Value " ])
eduDrop . head ()
If, instead of removing the rows containing NaN, we want to fill them with another
value, then we can use the fillna() method, specifying which value has to be used. If
we want to fill only some specific columns, we have to set as argument to the
fillna() function a dictionary with the name of the columns as the key and which
character to be used for filling as the value.
Sorting
Another important functionality we will need when inspecting our data is to sort
bycolumns. We can sort a DataFrame using any column, using the sortfunction. If
we want to see the first five rows of data sorted in descending order (i.e., from
the largest to the smallest values) and using the Value column, then we just need to
do this:
2.6 Get Started with Python for Data Scientists 23
Note that the inplace keyword means that the DataFrame will be overwritten, and
hence no new DataFrame is returned. If instead of ascending = False we use
ascending = True, the values are sorted in ascending order (i.e., from thesmallest
to the largest values).
If we want to return to the original order, we can sort by an index using the
sort_indexfunction and specifying axis=0:
Grouping Data
Another very useful way to inspect data is to group it according to some criteria.
For instance, in our example it would be nice to group all the data by country,
regardlessof the year. Pandas has the groupby function that allows us to do exactly
this. The value returned by this function is a special grouped DataFrame. To have
a proper DataFrame as a result, it is necessary to apply an aggregation function.
Thus, this function will be applied to all the values in the same group.
For example, in our case, if we want a DataFrame showing the mean of the
valuesfor each country over all the years, we can obtain it by grouping according to
country and using the mean function as the aggregation method for each group.
The result would be a DataFrame with countries as indexes and the mean values as
the gcrooluupm=n:edu [[ " GEO " , " Value " ]]. groupby ( ’ GEO ’). mean ()
In [24]: group . head ()
24 2 Toolboxes for Data Scientists
Out[24]: Value
GEO
Austria 5.618333
Belgium 6.189091
Bulgaria 4.093333
Cyprus 7.023333
Czech Republic 4.16833
Rearranging Data
Up until now, our indexes have been just a numeration of rows without much
meaning. We can transform the arrangement of our data, redistributing the indexes
and columns for better manipulation of our data, which normally leads to better
performance. Wecan rearrange our data using the pivot_tablefunction. Here, we
can specifywhich columns will be the new indexes, the new values, and the new
columns.
For example, imagine that we want to transform our DataFrame to a
spreadsheet- like structure with the country names as the index, while the
columns will be the years starting from 2006 and the values will be the previous
Value column. To do this, first we need to filter out the data and then pivot it in
this way:
f i l t e r e d _ d a t a = edu [ edu [" TIME "] > 2005]
pivedu = pd . pivot_table ( filtered_data , values = ’ Value ’,
index = [ ’ GEO ’],
columns = [ ’ TIME ’])
In [25]:
pivedu . head ()
Now we can use the new index to select specific rows by label, using the ix
operator:
than one value for the given row and column after the transformation. As usual,
you can design any custom function you want, just giving its name or using a λ-
function.
Ranking Data
Another useful visualization feature is to rank data. For example, we would like to
know how each country is ranked by year. To see this, we will use the pandas rank
function. But first, we need to clean up our previous pivoted table a bit so that it
only has real countries with real data. To do this, first we drop the Euro area
entries andshorten the Germany name entry, using the renamefunction and then
we drop allthe rows containing any NaN, using the dropnafunction.
Now we can perform the ranking using the rank function. Note here that the
parameter ascending=False makes the ranking go from the highest values to the
lowest values. The Pandas rank function supports different tie-breaking methods,
specified with the method parameter. In our case, we use the first method, in which
ranks are assigned in the order they appear in the array, avoiding gaps between
ranking.
In [27]: pivedu = pivedu.drop([
’Euro area ( 13 countri es ) ’,’Euro area (
15 countries)’,’Euro area (17 countri es
)’,’Euro area (18 countri es)’,
’ European Union ( 25 countri es ) ’, ’ European
Union ( 27 countri es ) ’, ’ Eur opean Union ( 28
countri es)’
],
axis = 0)
pivedu = p i vedu . rename ( index = { ’ G ermany ( until 1990 former t err it ory of the FRG)’: ’Germany’})
pivedu = pivedu.dropna()
pivedu.rank(as c ending = False, met hod = ’first’).head()
If we want to make a global ranking taking into account all the years, we can
sum up all the columns and rank the result. Then we can sort the resulting values
toretrieve the top five countries for the last 6 years, in this way:
In [28]: totalSum = pivedu . sum ( axis = 1)
totalSum . rank ( ascending = False , method = ’ dense ’)
. sort_values () . head ()
26 2 Toolboxes for Data Scientists
Out[28]: GEO
Denmark 1
Cyprus 2
Finland 3
Malta 4
Belgium 5
dtype: float64
Notice that the method keyword argument in the in the rank function specifies
how items that compare equals receive ranking. In the case of dense, items that
compare equals receive the same ranking number, and the next not equal item
receives the immediately following ranking number.
Plotting
Pandas DataFrames and Series can be plotted using the plot function, which uses the
library for graphics Matplotlib. For example, if we want to plot the accumulated
values for each country over the last 6 years, we can take the Series obtained in
theprevious example and plot it directly by calling the plot function as shown in the
next cell:
In [29]:
totalSum =
pivedu . sum ( axis = 1)
. sort_values ( ascending = False )
totalSum . plot ( kind = ’ bar ’, style = ’b ’, alpha = 0.4 ,
title = " Total Values for Country ")
Out[29]:
Note that if we want the bars ordered from the highest to the lowest value,
we need to sort the values in the Series first. The parameter kind used in the plot
function defines which kind of graphic will be used. In our case, a bar graph. The
parameter stylerefers to the style properties of the graphic, in our case, the color
Get Started
with Python for Data Scientists 27
of bars is set to b (blue). The alpha channel can be modified adding a keyword
parameter alpha with a percentage, producing a more translucent plot. Finally,using
the titlekeyword the name of the graphic can be set.
It is also possible to plot a DataFrame directly. In this case, each column is treated
as a separated Series. For example, instead of printing the accumulated value
over the years, we can plot the value for each year.
In [30]: my_colors = [ ’b ’, ’r ’, ’g ’, ’y ’, ’m ’, ’c ’]
ax = pivedu . plot ( kind = ’ barh ’,
stacked = True ,
color = my_colors )
ax . legend ( loc = ’ center left ’, bbox_to_anchor = (1 , .5 ) )
Out[30]:
In this case, we have used a horizontal bar graph (kind=’barh’) stacking all the
years in the same country bar. This can be done by setting the parameter stacked
to True. The number of default colors in a plot is only 5, thus if you have more
than 5 Series to show, you need to specify more colors or otherwise the same set
ofcolors will be used again. We can set a new set of colors using the keyword color
with a list of colors. Basic colors have a single-character code assigned to each,
for example, “b” is for blue, “r” for red, “g” for green, “y” for yellow, “m” for
magenta, and “c” for cyan. When several Series are shown in a plot, a legend is
created for identifying each one. The name for each Series is the name of the
column in the DataFrame. By default, the legend goes inside the plot area. If we
want to change this, we can use the legend function of the axis object (this is the
object returned when the plot function is called). By using the loc keyword, we can
set the relative position of the legend with respect to the plot. It can be a
combination of right or left and upper, lower, or center. With bbox_to_anchor we
can set an absolute position with respect to the plot, allowing us to put the
legend outside the graph.
UNIT-2
Descriptive statistics, data preparation. Exploratory Data Analysis data summarization,
data distribution, measuring asymmetry. Sample and estimated mean, variance and
standard score. Statistical Inference frequency approach, variability of estimates,
hypothesis testing using confidence intervals, using p-values
DescriptiveStatistics
Descriptive statistics applies the concepts, measures, and terms that are used
to describe the basic features of the samples in a study. These procedures are
essential to provide summaries about the samples as an approximation of the
population. Together with simple graphics, they form the basis of every
quantitative analysis ofdata. In order to describe the sample data and to be able
to infer any conclusion, weshould go through several steps:
Data Preparation
One of the first tasks when analyzing data is to collect and prepare the data in a
format appropriate for analysis of the samples. The most common steps for data
preparationinvolve the following operations.
1. Obtaining the data: Data can be read directly from a file or they might be obtained
by scraping the web.
2. Parsing the data: The right parsing procedure depends on what format the
dataare in: plain text, fixed columns, CSV, XML, HTML, etc.
3. Cleaning the data: Survey responses and other data files are almost always in-
complete. Sometimes, there are multiple codes for things such as, not asked,
did not know, and declined to answer. And there are almost always errors. A
simplestrategy is to remove or ignore incomplete records.
4. Building data structures: Once you read the data, it is necessary to store them
ina data structure that lends itself to the analysis we are interested in. If the
data fit into the memory, building a data structure is usually the way to go. If
not, usually a database is built, which is an out-of-memory data structure.
Most databases provide a mapping from keys to values, so they serve as
dictionaries.
Let us consider a public database called the “Adult” dataset, hosted on the UCI’s
Machine Learning Repository.1 It contains approximately 32,000 observations con-
cerning different financial parameters related to the US population: age, sex,
marital(marital status of the individual), country, income (Boolean variable: whether
the per- son makes more than $50,000 per annum), education (the highest level of
educationachieved by the individual), occupation, capital gain, etc.
We will show that we can explore the data by asking questions like: “Are men
more likely to become high-income professionals than women, i.e., to receive an
income of over $50,000 per annum?”
Data Preparation
data = []
for line in file :
data 1 = line . split ( ’, ’)
if len ( data 1 ) == 15 :
data . append ([ chr_int ( data1 [0 ]) , data 1 [1] ,
chr_int ( data1 [2 ]) , data1 [3] ,
chr_int ( data1 [4 ]) , data1 [5] ,
data 1 [6] , data 1 [7] , data 1 [8] ,
data 1 [9] , chr_int ( data1 [10]) ,
chr_int ( data 1 [ 11 ]) ,
chr_int ( data1 [12]) ,
data 1 [13] , data 1 [14]
])
The command shapegives exactly the number of data samples (in rows, in this
case) and features (in columns):
In[4]: df . shape
Thus, we can see that our dataset contains 32,561 data records with 15
featureseach. Let us count the number of items per country:
In[5]:
counts = df . groupby ( ’ country ’). size ()
print counts . head ()
Out[5]: country
? 583
Cambodia 19
Vietnam 67
Yugoslavia 16
The first row shows the number of samples with unknown country, followed
bythe number of samples corresponding to the first countries in the dataset.
Let us split people according to their gender into two groups: men and women.
In[6]:
ml = df [( df . sex == ’ Male ’)]
The data that come from performing a particular measurement on all the
subjects in a sample represent our observations for a single characteristic like
country, age, education, etc. These measurements and categories represent a
sample distribution of the variable, which in turn approximately represents the
population distribution of the variable. One of the main goals of exploratory
data analysis is to visualize and summarize the sample distribution, thereby
allowing us to make tentative assumptions about the population distribution.
Summarizing the Data
In[8]:
df 1 = df [( df . income == ’ >50 K\ n ’)]
print ’ The rate of people with high income is : ’,
int ( len ( df1 )/ float ( len ( df )) *100 ) , ’%. ’
print ’ The rate of men with high income is : ’,
int ( len ( ml1 )/ float ( len ( ml )) *100 ) , ’%. ’
print ’ The rate of women with high income is : ’,
int ( len ( fm1 )/ float ( len ( fm )) * 100) , ’%. ’
Mean
One of the first measurements we use to have a look at the data is to obtain
samplestatistics from the data, such as the sample mean [1]. Given a sample of
n values,
{ x}i ,i = 1 , . . . , n, the mean, μ, is the sum of the values divided by the number of
values,2 in other words:
n
1
μ= ix . (3.1)
n
i=1
The terms mean and average are often used interchangeably. In fact, the
maindistinction between them is that the mean of a sample is the summary
statistic com-puted by Eq. (3.1), while an average is not strictly defined and could
be one of manysummary statistics that can be chosen to describe the central
tendency of a sample.
In our case, we can consider what the average age of men and women samples
inour dataset would be in terms of their mean:
Descriptive Statistics
In[9]:
print ’ The average age of men is : ’,
ml [ ’ age ’]. mean ()
print ’ The average age of women is : ’,
fm [ ’ age ’]. mean ()
Out[9]: The average age of men is: 39.4335474989 The average age of
women is: 36.8582304336
The average age of high-income men is: 44.6257880516
The average age of high-income women is: 42.1255301103
This difference in the sample means can be considered initial evidence that
thereare differences between men and women with high income!
Comment: Later, we will work with both concepts: the population mean and
thesample mean. We should not confuse them! The first is the mean of samples
takenfrom the population; the second, the mean of the whole population.
Sample Variance
The mean is not usually a sufficient descriptor of the data. We can go further by
knowing two numbers: mean and variance. The variance σ2 describes the spread
ofthe data and it is defined as follows:
1
σ2 = (x − μ)2. (3.2)
i
n i
The term (xi −μ ) is called the deviation from the mean, so the variance is the mean
squared deviation. The square root of the variance, σ, is called the standard
deviation. We consider the standard deviation, because the variance is hard to
interpret (e.g., ifthe units are grams, the variance is in grams squared).
Let us compute the mean and the variance of hours per week men and women
inour dataset work:
In[10]: ml_mu = ml [ ’ age ’]. mean ()
fm_mu = fm [ ’ age ’]. mean ()
ml_var = ml [ ’ age ’]. var ()
fm_var = fm [ ’ age ’]. var ()
ml_std = ml [ ’ age ’]. std ()
fm_std = fm [ ’ age ’]. std ()
print ’ Statistics of age for men : mu : ’,
3.3 Exploratory Data Analysis 35
Out[10]: Statistics of age for men: mu: 39.4335474989 var: 178.773751745std: 13.3706301925
Statistics of age for women: mu: 36.8582304336 var:196.383706395 std:
14.0136970994
We can see that the mean number of hours worked per week by women is signif-
icantly lesser than that worked by men, but with much higher variance and
standarddeviation.
Sample Median
The mean of the samples is a good descriptor, but it has an important drawback:
what will happen if in the sample set there is an error with a value very different
from the rest? For example, considering hours worked per week, it would
normally be in a range between 20 and 80; but what would happen if by mistake
there was a value of 1000? An item of data that is significantly different from the
rest of the data is called an outlier. In this case, the mean, μ, will be drastically
changed towards the outlier. One solution to this drawback is offered by the
statistical median, μ12, which is an order statistic giving the middle value of a
sample. In this case, all the values are ordered by their magnitude and the
median is defined as the value that is in themiddle of the ordered list. Hence, it is
a value that is much more robust in the face of outliers.
Let us see, the median age of working men and women in our dataset and the
median age of high-income men and women:
Fig. 3.1 Histogram of the age of working men (left) and women (right)
That value, xp, is the p-th quantile, or the 100 p×-th percentile. For example, a 5-
number summary is defined by the values xmin, Q1, Q2, Q3, xmax , where Q1 is the
25 p-th×percentile, Q2 is the 50 p-th pe×rcentile and Q3 is the 75 p-th perce× ntile.
Data Distributions
Summarizing data by just looking at their mean, median, and variance can be danger-
ous: very different data can be described by the same statistics. The best thing to
do is to validate the data by inspecting them. We can have a look at the data
distribution, which describes how often each value appears (i.e., what is its
frequency).
The most common representation of a distribution is a histogram, which is a graph
that shows the frequency of each value. Let us show the age of working men and
women separately.
In[12]:
ml_age = ml [ ’ age ’]
ml_age . hist ( normed = 0 , histtype = ’ stepfilled ’,
bins = 20 )
In[13]:
fm_age = fm [ ’ age ’]
fm_age . hist ( normed = 0 , histtype = ’ stepfilled ’,
bins = 10 )
The output can be seen in Fig. 3.1. If we want to compare the histograms, we
canplot them overlapping in the same graphic as follows:
3.3 Exploratory Data Analysis 37
Fig. 3.2 Histogram of the age of working men (in ochre) and women (in violet) (left). Histogram of the
age of working men (in ochre), women (in blue), and their intersection (in violet) after samples
normalization (right)
In[14]:
import seaborn as sns
fm_age . hist ( normed = 0 , histtype = ’ stepfilled ’,
alpha = .5 , bins = 20 )
ml_age . hist ( normed = 0 , histtype = ’ stepfilled ’,
alpha = .5 ,
color = sns . desaturate (" india nred " ,
.75) ,
bins = 10 )
The output can be seen in Fig. 3.2 (left). Note that we are visualizing the absolute
values of the number of people in our dataset according to their age (the abscissa
ofthe histogram). As a side effect, we can see that there are many more men in
these conditions than women.
We can normalize the frequencies of the histogram by dividing/normalizing by
n, the number of samples. The normalized histogram is called the Probability
MassFunction (PMF).
This outputs Fig. 3.2 (right), where we can observe a comparable range of indi-
viduals (men and women).
The Cumulative Distribution Function (CDF), or just distribution function,
describes the probability that a real-valued random variable X with a given proba-
bility distribution will be found to have a value less than or equal to x . Let us show
the CDF of age distribution for both men and women.
38 3 Descriptive Statistics
In[16]:
ml_age . hist ( normed = 1 , histtype = ’ step ’,
cumulative = True , linewidth = 3.5 ,
bins = 20 )
fm_age . hist ( normed = 1 , histtype = ’ step ’,
cumulative = True , linewidth = 3.5 ,
bins = 20 ,
color = sns . desaturate (" india nred " ,
.75) )
The output can be seen in Fig. 3.3, which illustrates the CDF of the age distributions
for both men and women.
Outlier Treatment
As mentioned before, outliers are data samples with a value that is far from the
centraltendency. Different rules can be defined to detect outliers, as follows:
For example, in our case, we are interested in the age statistics of men versus
women with high incomes and we can see that in our dataset, the minimum age is
17years and the maximum is 90 years. We can consider that some of these samples
are due to errors or are not representable. Applying the domain knowledge, we
focus onthe median age (37, in our case) up to 72 and down to 22 years old, and
we considerthe rest as outliers.
3.3 Exploratory Data Analysis 39
In[17]:
df 2 = df . drop ( df . index [
( df . income == ’ >50 K\ n ’) &
(df[ ’ age ’] > df [ ’ age ’]. median () + 35 ) &
(df[ ’ age ’] > df [ ’ age ’]. median () - 15)
])
ml1_age = ml 1 [ ’ age ’]
fm1_age = fm 1 [ ’ age ’]
We can check how the mean and the median changed once the data were cleaned:
In[18]: mu 2ml = ml 2 _age . mean ()
std2ml = ml 2 _age . std ()
md 2ml = ml 2 _age . median ()
mu 2fm = fm2 _age . mean ()
std2fm = fm 2 _age . std ()
md 2fm = fm 2 _age . median ()
Fig. 3.4 The red shows the cleaned data without the considered outliers (in blue)
Figure 3.4 shows the outliers in blue and the rest of the data in red. Visually,
wecan confirm that we removed mainly outliers from the dataset.
Next we can see that by removing the outliers, the difference between the
popula-tions (men and women) actually decreased. In our case, there were more
outliers inmen than women. If the difference in the mean values before removing
the outliersis 2.5, after removing them it slightly decreased to 2.44:
In[20]: print ’ The mean differenc e with outliers is : %4.2 f.
’
% ( ml_age . mean () - fm_age . mean () )
print ’ The mean differen ce without outliers is :
%4.2 f. ’
% ( ml2_age . mean () - fm2_age . mean () )
The results are shown in Fig. 3.5. One can see that the differences between
male and female values are slightly negative before age 42 and positive after it.
Hence, women tend to be promoted (receive more than 50 K) earlier than men.
3.3 Exploratory Data Analysis 41
Fig. 3.5 Differences in high-income earner men versus women as a function of age
For univariate data, the formula for skewness is a statistic that measures the
asym-metry of the set of n data samples, xi :
.
g = 1 i(xi − μ ) ,
3
(3.3)
1 n σ 3
where μ is the mean, σ is the standard deviation, and n is the number of data points.
Negative deviation indicates that the distribution “skews left” (it extends
further to the left than to the right). One can easily see that the skewness for a
normal distribution is zero, and any symmetric data must have a skewness of
zero. Note that skewness can be affected by outliers! A simpler alternative is to
look at the relationship between the mean μ and the median μ12.
In[22]:
def skewness ( x):
res = 0
m = x. mean ()
s = x. std ()
for i in x:
res += ( i - m) * ( i - m) * ( i - m)
res /= ( len ( x) * s * s * s)
return res
Out[23]: Pearson’s coefficient of the male population = 9.55830402221 Pearson’s coefficient of the
female population = 26.4067269073
Continuous Distribution
Fig. 3.6 Exponential CDF (left) and PDF (right) with λ = 3.00
¸x
is defined as FX(x) where this satisfies: FX (x) = f X(t)δt for all x. There are
∞
many continuous distributions; here, we will consider the most common ones: the
exponential and the normal distributions.
4e e 2
44 3 Descriptive Statistics
Kernel Density
y Data Analysis 45
Fig. 3.8 Summed kernel functions around a random set of points (left) and the kernel density
estimate with the optimal bandwidth (right) for our dataset. Random data shown in blue, kernel
shown in black and summed function shown in red
a continuous function that when normalized would approximate the density of the
distribution:
In[24]: x1 = np . random . normal ( -1 , 0.5 , 15 )
x2 = np . random . normal (6 , 1 , 10 )
y = np .r_[ x1 , x2 ] # r_ t ranslate s slice objects to
conc ate nat ion along the first axis .
x = np . linspace ( min ( y) , max ( y) , 100)
Figure 3.8 (left) shows the result of the construction of the continuous
functionfrom the kernel summarization.
In fact, the library SciPy3 implements a Gaussian kernel density estimation that
automatically chooses the appropriate bandwidth parameter for the kernel. Thus,
thefinal construction of the density estimate will be obtained by:
.
46 3 Descriptive Statistics
In[25]:
from scipy . stats import kde
density = kde . gaus sia n_k de ( y)
xgrid = np . linspace ( x. min () , x. max () , 200)
plt . hist (y , bins = 28 , normed = True )
plt . plot ( xgrid , density ( xgrid ) , ’r-’)
Figure 3.8 (right) shows the result of the kernel density estimate for our example.
Estimation
An important aspect when working with statistical data is being able to use
estimatesto approximate the values of unknown parameters of the dataset. In this
section, we will review different kinds of estimators (estimated mean, variance,
standard score,etc.).
In continuation, we will deal with point estimators that are single numerical estimates
of parameters of a population.
Mean
Let us assume that we know that our data are coming from a normal distribution
andthe random samples drawn are as follows:
{0.33, −1.76, 2.34, 0.56, 0.89}.
The question is can we guess the mean μ of the distribution? One approximation
isgiven by the sample mean,¯x . This process is called estimation and the statistic (e.g.,
the sample mean) is called an estimator. In our case, the sample mean is 0.472, and
it seems a logical choice to represent the mean of the distribution. It is not so
evident ifwe add a sample with —a value of 465. In this case, the sample mean− will be
77.11, which does not look like the mean of the distribution. The reason is due to
the fact that the last value seems to be an outlier compared to the rest of the
sample. In orderto avoid this effect, we can try first to remove outliers and then to
estimate the mean; or we can use the sample median as an estimator of the
mean of the distribution.If there are no¯ outliers, the sample mean x minimizes
the following mean squared error:
1
MSE = ¯ − (x μ) ,
2
n
where n is the number of times we estimate the
mean.Let us compute the MSE of a set of random
data:
3.4 Estimation 47
In[26]:
NTs = 200
mu = 0.0
var = 1.0
err = 0.0
NPs = 1000
for i in range ( NTs ):
x = np . random . normal ( mu , var , NPs )
err += ( x. mean () - mu ) ** 2
print ’ MSE : ’, err / NTests
Variance
If we ask ourselves what is the variance, σ2, of the distribution of X , analogously
we can use the sample variance as an estimator. Let us den¯ote by σ2 the sample
varianceestimator:
1
¯σ =
2
−¯i(x x) .
2
n
For large samples, this estimator works well, but for a small number of
samplesit is biased. In those cases, a better estimator is given by:
1
σ̄2 = (xi − x¯)2.
n−1
Standard Score
In many real problems, when we want to compare data, or estimate their
correlations or some other kind of relations, we must avoid data that come in
different units. For example, weight can come in kilograms or grams. Even data
that come in the same units can still belong to different distributions. We need to
normalize them tostandard scores. Given a dataset a{s a}series of values, xi , we
convert the data to standard scores by subtracting the mean and dividing them by
the standard deviation:
(xi − μ)
zi= .
σ
Note that this measure is dimensionless and its distribution has a mean of 0
and variance of 1. It inherits the “shape” of the dataset: if X is normally
distributed, so is Z; if X is skewed, so is Z.
Variables of data can express relations. For example, countries that tend to invest
in research also tend to invest more in education and health. This kind of
relationshipis captured by the covariance.
48 3 Descriptive Statistics
Fig. 3.9 Positive correlation between economic growth and stock market returns worldwide ( left).
Negative correlation between the world oil production and gasoline prices worldwide (right)
Covariance
When two variables share the same tendency, we speak about covariance. Let us
consider two series,{xi a}nd y{i . }Let us center the data with respect to their mean:
dxi =xi μ −X and d yi y= i μ−Y . It is easy to show that when x{i }and {yi } vary
together, their deviations tend to have the same sign. The covariance is defined
as the mean of the following products:
n
1
Cov(X, Y) =n dix dy ,
i=i1
where n is the length of both sets. Still, the covariance itself is hard to interpret.
having ρ 0=, does not necessarily mean that the variables are not correlated! Pear-
son’s correlation captures correlations of first order, but not nonlinear
correlations.Moreover, it does not work well in the presence of outliers.
between the sets. However, the Spearman’s rank coefficient, capturing the
correlation between the ranks, gives as a final value of 0.80, confirming the
correlation betweenthe sets. As an exercise, you can compute the Pearson’s and
the Spearman’s rank correlations for the different Anscombe configurations given in
Fig. 3.10. Observe if linear and nonlinear correlations can be captured by the
Pearson’s and the Spearman’s rank correlations.
Statistical Inference
Introduction
There is not only one way to address the problem of statistical inference. In fact,
there are two main approaches to statistical inference: the frequentist and
Bayesianapproaches. Their differences are subtle but fundamental:
• In the case of the frequentist approach, the main assumption is that there is a
population, which can be represented by several parameters, from which we
can obtain numerous random samples. Population parameters are fixed but
they are not accessible to the observer. The only way to derive information
about these parameters is to take a sample of the population, to compute the
parameters of the sample, and to use statistical inference techniques to make
probable propositionsregarding population parameters.
• The Bayesian approach is based on a consideration that data are fixed, not the
result of a repeatable sampling process, but parameters describing data can be
described probabilistically. To this end, Bayesian inference methods focus on
producing parameter distributions that represent all the knowledge we can
extract from the sample and from prior information about the problem.
In[1]:
Sampling Distribution of Point Estimates
Let us suppose that we are interested in describing the daily number of traffic
acci- dents in the streets of Barcelona in 2013. If we have access to the
population, the computation of this parameter is a simple operation: the total
number of accidents divided by 365.
data = pd . read_csv (" files / ch04 / ACCIDENTS_GU_BCN_ 2013 . csv ")
data [ ’ Date ’] = data [ u ’ Dia de mes ’]. apply ( lambda x: str (x))
+ ’-’ +
data [ u ’ Mes de any ’]. apply ( lambda x: str (x))
data [ ’ Date ’] = pd . to_datetime ( data [’ Date ’])
suppose that we only have access to a limited part of the data (the
Out[1]: sample): the number of accidents during some days of 2013. Can we
Mean: still give an approximation of the population mean?
25.9095 The most intuitive way to go about providing such a mean is simply
B to take the sample mean. The sample mean is a point estimate of the
u population mean. If we can only choose one value to estimate the
t population mean, then this is our best guess.
The problem we face is that estimates generally vary from one
n sample to another, and this sampling variation suggests our estimate
o may be close, but it will not be exactly equal to our parameter of
w interest. How can we measure this variability?
, In our example, because we have access to the population, we can
empirically buildthe sampling distribution of the sample mean2 for a
f given number of observations.Then, we can use the sampling
o distribution to compute a measure of the variability.In Fig. 4 .=1 , we can
r see t = h e empirical sample distribution of the mean for s 10.000 sam
200 observations from our dataset. This empirical distribution has
i been built in the following way: Statistical Inference
l
l
u
s
t
r
a
t
i
v
e
Fig. 4.1 Empirical distribution of the sample mean. In red, the mean value of this distribution
p
u
1. Draw s (a large number) independent samples { x 1 , . . ., xs} from the
r
populationwhere each element x j is composed of {x j}i=1,...,n.
p i
o 2. Evaluate the sample mean μˆ j = 1 .n x j of each sample.
n i=1 i
3. Estimate the sampling distr ibution of μby the empirical distribution of the
s ˆ
sample
e
replications.
s
,
In [2#]: population
df = accidents . to_frame ()
l N_test = 10000
e elements = 200
# mean array of samples
t means = [ 0 ] * N_test
# sample generation
for i in range ( N_test ):
u rows = np. random . choice ( df. index . values , elements )
sampled_df = df . ix [ rows ]
s means [ i] = sampled_df . mean ()
te from a sample of size n, we define its samplingdistribution as the
distribution of the point estimate based on samples of size n from its
I
population. This definition is valid for point estimates of other
n
population parameters, such as the population median or population
standard deviation, but we will focus on the analysis of the sample
g
e mean.
The sampling distribution of an estimate plays an important role in
n
understanding the real meaning of propositions concerning point
e
estimates. It is very useful to think of a particular point estimate as
r
a being drawn from such a distribution.
l The Traditional Approach
In real problems, we do not have access to the real population and
,
so estimation of the sampling distribution of the estimate from the
empirical distribution of the sample replications is not an option. But
g
this problem can be solved by making use of some theoretical results
i
from traditional statistics.
v
e
4.3 Measuring the Variability in Estimates 55
n
It can be mathematically shown that given n independent observatio{ ns} xi i=1,..,n
aof a population with a standard deviation σx , the standard deviation of the
samplemean σx¯, or standard error, can be approximated by this formula:
p σx
SE = √
o n
i The demonstration of this result is based on the Central Limit Theorem: an
noldtheorem with a history that starts in 1810 when Laplace released his first paper
t on it.This formula uses the standard deviation of the population σx , which is not
known, but it can be shown that if it is substituted by its empiricaˆl estimate σx , the
e estimationis sufficiently good if n > 30 and the population distribution is not
sskewed. Thisallows us to estimate the standard error of the sample mean even if
t we do not have
iaccess to the population.
m So, how can we give a measure of the variability of the sample mean? The
answeris simple: by giving the empirical standard error of the mean distribution.
Out[3]: Direct estimation of SE from one sample of 200 elements: 0.6536Estimation of the SE by
simulating 10000 samples of 200
elements: 0.6362
Unlike the case of the sample mean, there is no formula for the standard error
ofother interesting sample estimates, such as the median.
The Computationally Intensive Approach
Let us consider from now that our full dataset is a sample from a hypothetical
population (this is the most common situation when analyzing real data!).
A modern alternative to the traditional approach to statistical inference is the
bootstrapping method [2]. In the bootstrap, we draw n observations with
replacement from the original data to create a bootstrap sample or resample. Then,
we can calculate the mean for this resample. By repeating this process a large
number of times, we can build a good approximation of the mean sampling
distribution (see Fig. 4.2).
56 4 Statistical Inference
Fig. 4.2 Mean sampling distribution by bootstrapping. In red, the mean value of this distribution
Confidence Intervals
A point estimate Θ, such as the sample mean, provides a single plausible value
fora parameter. However, as we have seen, a point estimate is rarely perfect;
usually there is some error in the estimate. That is why we have suggested using the
standard error as a measure of its variability.
Instead of that, a next logical step would be to provide a plausible range of
valuesfor the parameter. A plausible range of values for the sample parameter is
called a confidence interval.
We will base the definition of confidence interval on two ideas:
1. Our point estimate is the most plausible value of the parameter, so it makes
senseto build the confidence interval around the point estimate.
2. The plausibility of a range of values can be defined from the sampling
distributionof the estimate.
For the case of the mean, the Central Limit Theorem states that its
samplingdistribution is normal:
Theorem 4.1 Given a population with a finite mean μ and a finite non-zero variance σ
2
, the sampling distribution of the mean approaches a normal distribution with a
mean of μ and a variance of σ2/n as n, the sample size, increases.
In this case, and in order to define an interval, we can make use of a well-
knownresult from probability that applies to normal distributions: roughly 95% of
the timeour estimate will be within 1.96 standard errors of the true mean of the
distribution. If the interval spreads out 1.96 standard errors from a normally
distributed point estimate, intuitively we can say that we are roughly 95%
confident that we have captured the true parameter.
CI = [Θ − 1.96 × SE, Θ + 1.96 × SE ]
This is how we would compute a 95% confidence interval of the sample mean
using bootstrapping:
1. Repeat the following steps for a large number, s, of times:
2. Calculate the mean of your s values of the sample statistic. This process
givesyou a “bootstrapped” estimate of the sample statistic.
3. Calculate the standard deviation of your s values of the sample statistic.
Thisprocess gives you a “bootstrapped” estimate of the SE of the sample
statistic.
4. Obtain the 2.5th and 97.5th percentiles of your s values of the sample statistic.
In 95% of the cases, when I compute the 95% confidence interval from this sample, the
true mean of the population will fall within the interval defined by these bounds: ±1.96 ×
SE.
We cannot say either that our specific sample contains the true parameter or
that the interval has a 95% chance of containing the true parameter. That
interpretation would not be correct under the assumptions of traditional
statistics.
Hypothesis Testing
• H0: The mean number of daily traffic accidents is the same in 2010 and 2013
(there is only one population, one true mean, and 2010 and 2013 are just
differentsamples from the same population).
• HA: The mean number of daily traffic accidents in 2010 and 2013 is different
(2010 and 2013 are two samples from two different populations).
Fig. 4.3 This graph shows 100 sample means (green points) and its corresponding confidence
intervals, computed from 100 different samples of 100 elements from our dataset. It can be
observed that a few of them (those in red) do not contain the mean of the population (black
horizontal line)
60 4 Statistical Inference
We call H0 the null hypothesis and it represents a skeptical point of view: the
effect we have observed is due to chance (due to the specific sample bias). HA is
thealternative hypothesis and it represents the other point of view: the effect is
real.
The general rule of frequentist hypothesis testing: we will not discard H0 (and
hence we will not consider HA) unless the observed effect is implausible under
H0.
This estimate suggests that in 2013 the mean rate of traffic accidents in
Barcelonawas higher than it was in 2010. But is this effect statistically significant?
Based on our sample, the 95% confidence interval for the mean rate of
trafficaccidents in Barcelona during 2013 can be calculated as follows:
If we use a 95% confidence interval to test a problem where the null hypothesis is true,
we will make an error whenever the point estimate is at least 1.96 standard errors away
from thepopulation parameter. This happens about 5% of the time (2.5% in each tail).
• The second step is to define a null hypothesis, which is a model of the system
based on the assumption that the apparent effect is not real. In our case, the
null hypothesis is that there is no difference between the two periods.
• The third step is to compute a p-value, which is the probability of seeing the
apparent effect if the null hypothesis is true. In our case, we would compute
the difference in means, then compute the probability of seeing a difference as
big, orbigger, under the null hypothesis.
• The last step is to interpret the result. If the p-value is low, the effect is said to
be statistically significant, which means that it is unlikely to have occurred by
chance. In this case we infer that the effect is more likely to appear in the larger
population.
p = ( c o u n t s 2 0 1 3 . m e an () - c o u n t s 2 0 1 0 . mean () )
print ’m: ’, m , ’n: ’, n
p r i nt ’ mean d i f f e r e n c e : ’, p
1. Pool the distributions, generate samples with size n and compute the
differencein the mean.
2. Generate samples with size n and compute the difference in the mean.
3. Count how many differences are larger than the observed one.
In [10]:
# pooling distributions
x = counts2010
y = counts 2013
po o l = np . c o n c a t e n a t e ([ x , y ])
np . r a n d o m . shuffle ( pool )
# sample g e n e r a t i o n
import random
N = 10000 # number of samples
di f f = range (N)
for i in range ( N ) :
di f f [ i] = ( np . mean ( p1 ) - np . mean ( p2 ))
Hypothesis Testing
We do not yet have an answer for this question! We have defined a null
hypothesisH0 (the effect is not real) and we have computed the probability of the
observed effect under the null hypothesis, wh |ich is P(E H0), where E is an effect
as big as or bigger than the apparent effect and a p-value .
We have stated that from the frequentist point of view, we cannot consider HA
unless P(E H| 0) is less than an arbitrary value. But the real answer to this question
must be based on comparing P(H0|E) to P(HA E|), not on P(E H0|)! One possi- ble
solution to these problems is to use Bayesian reasoning; an alternative to the
frequentist approach.
No matter how many data you have, you will still depend on intuition to
decide how to interpret, explain, and use that data. Data cannot speak by
themselves. Data scientists are interpreters, offering one interpretation of what
the useful narrative story derived from the data is, if there is one at all.
UNIT-3
Supervised Learning: First step, learning curves, training-validation and test.
Learning models generalities, support vector machines, random forest.
Examples
Supervised Learning
Machine learning involves coding programs that automatically adjust their
perfor- mance in accordance with their exposure to information in data. This
learning is achieved via a parameterized model with tunable parameters that are
automatically adjusted according to different performance criteria. Machine
learning can be con- sidered a subfield of artificial intelligence (AI) and we can
roughly divide the fieldinto the following three major classes.
Supervised Learning
– Given the results of a clinical test, e.g., does this patient suffer from diabetes?
– Given a magnetic resonance image, is it a tumor shown in the image?
– Given the past activity associated with a credit card, is the current
operationfraudulent?
Observe that some problems can be solved using both regression and
classification. As we will see later, many classification algorithms are thresholded
regressors. There is a certain skill involved in designing the correct question and
this dramatically affects the solution we obtain.
The Problem
In this chapter we use data from the Lending Club 1 to develop our understanding
of machine learning concepts. The Lending Club is a peer-to-peer lending
company. It offers loans which are funded by other people. In this sense, the
Lending Club acts as a hub connecting borrowers with investors. The client applies
for a loan of acertain amount, and the company assesses the risk of the operation.
If the applicationis accepted, it may or may not be fully covered. We will focus
on the predictionof whether the loan will be fully funded, based on the scoring
of and information related to the application.
We will use the partial dataset of period 2007–2011. Framing the problem a
little bit more, based on the information supplied by the customer asking for a
loan, we want to predict whether it will be granted up to a certain threshold thr . The
attributes we use in this problem are related to some of the details of the loan
application, such as amount of the loan applied for the borrower, monthly
payment to be made by the borrower if the loan is accepted, the borrower’s
annual income, the number of incidences of delinquency in the borrower’s credit
file, and interest rate of the loan,among others.
In this case we would like to predict unsuccessful accepted loans. A loan
applica-tion is unsuccessful if the funded amount (funded_amnt) or the amount
funded by investors (funded_amnt_inv) falls far short of the requested loan
amount (loan_amnt). That is,
loan − f unded
loan ≥ 0.95.
First Steps
Note that in this problem we are predicting a binary value: either the loan is fully
funded or not. Classification is the natural choice of machine learning tools for
prediction with discrete known outcomes. According to the cardinality of the
target set, one usually distinguishes between binary classifiers when the target
output onlytakes two values, i.e., the classifier answers questions with a yes or a no;
or multiclass classifiers, for a larger number of classes. This issue is important in
that not all methods can naturally handle the multiclass setting.2
In a formal way, classification is regarded as the problem of finding a function
h(x) :Rd → K that maps an input space in Rd onto a discrete set of k target outputs
or classes K = {1 , . . . , k .}In this setting, the features are arranged as a vector x ofd
real-valued numbers.3
We can encode both target states in a numerical variable, e.g., a successful
loan target can take v+alue 1; and i−
t is 1, otherwise.
Let us check the dataset,4
import pickle
ofname = open ( ’./ files / ch05 / dataset_small . pkl ’,’rb ’)
# x stores input data and y target values
(x , y) = pickle . load ( ofname )
In[1]:
are capable of coping with this kind of data or we need to change the representation of those
variables into numerical values.
4The notebook companion shows the preprocessing steps, from reading the dataset, cleaning and
• Input data is structured in Numpy arrays. The size of the array is expected to be
[n_samples, n_features]:
All objects in Scikit-learn share a uniform and limited API consisting of three
complementary interfaces:
Out[4]: 0.83164251207729467
It looks like a really good result. But how good is it? Let us first understand a little
bit more about the problem by checking the distribution of the labels.
Let us load the dataset and check the distribution of labels:
In [5]: plt . pie ( np . c_ [ np . sum ( np . where ( y == 1 , 1 , 0) ) ,
np . sum ( np . where ( y == -1 , 1 , 0) ) ][0] ,
labels = [ ’ Not fully funded ’,’ Full amount ’],
colors = [ ’r ’, ’g ’], shadow = False ,
autopct = ’ %.2 f ’ )
plt . gcf () . set_size_inches ((7 , 7) )
5The term unbalanced describes the condition of data where the ratio between positives and
negatives is a small value. In these scenarios, always predicting the majority class usually yields
accurate performance, though it is not very informative. This kind of problems is very common
when we want to model unusual events such as rare diseases, the occurrence of a failure in
machinery, fraudulent credit card operations, etc. In these scenarios, gathering data from usual
events is very easy but collecting data from unusual events is difficult and results in a
comparatively small dataset.
Fig. 5.1 Pie chart showing
the distribution of labels
inthe dataset
majority class, will give us good performance. In our problem, always predicting
that the loan will be fully funded correctly predicts 81.57% of the samples.
Observethat this value is very close to that obtained using the classifier.
Although accuracy is the most normal metric for evaluating classifiers, there
arecases when the business value of correctly predicting elements from one class
is different from the value for the prediction of elements of another class. In
those cases, accuracy is not a good performance metric and more detailed
analysis is needed. The confusion matrix enables us to define different metrics
considering such scenarios. The confusion matrix considers the concepts of the
classifier outcome and the actual ground truth or gold standard. In a binary
problem, there are four possiblecases:
• True positives (TP): When the classifier predicts a sample as positive and it really
is positive.
• False positives (FP): When the classifier predicts a sample as positive but in fact
it is negative.
• True negatives (TN): When the classifier predicts a sample as negative and it really
is negative.
• False negatives (FN): When the classifier predicts a sample as negative but in fact
it is positive.
Gold Standard
Positive Negative
Positive TP FP → Precision
Prediction Negative FN TN → Negative Predictive Value
↓
Sens itivity
↓
Spec ificity (Recall)
• Accuracy:
TP + TN
accuracy
=
TP + TN + FP + FN
• Column-wise we find these two partial performance metrics:
– Sensitivity or Recall:
TP TP
sensitivity = =
Real Positives TP + FN
– Specificity: TN TN
specificity = =
Real Negatives TN + FP
• Row-wise we find these two partial performance metrics:
In [6]:
= np . sum ( np . l o g i c a l _ a n d ( yhat == -1 , y == -1) )
= == 1 , y == 1) )
= == -1 , y == 1) )
= == 1 , y == -1) )
p r i nt ’ TP : ’ + str ( T P ) , ’, FP : ’ + st r (FP)
p r i nt ’ FN : ’ + str ( F N ) , ’, TN : ’ + str ( T N )
Let us check the following example. Let us select a nearest neighbor classifier
with the number of neighbors equal to one instead of eleven, as we did before,
andcheck the training error.
In [8]: # Train a classifier using . fit ()
knn = neighbors . KNeighbors Classifier ( n_neighbors = 1)
knn. fit ( x , y)
yhat = knn . predict ( x)
Out[10]:TRAINING STATS:
classification accuracy: 1.0
confusion matrix:
2355 0
0 543
As expected from the former experiment, we achieve a perfect score. Now let
ussee what happens in the simulation with previously unseen data.
In [11]:
# C h ec k on t he test set
yh a t = knn . p r e d i c t ( X_test )
print " TESTING STATS :"
print " classification accuracy :" ,
metrics . accuracy_score ( yhat , y_test )
p r i nt " c o n f u s i o n m a t r i x : \ n" +
str ( metrics . c on f us ion _ ma t ri x ( yhat , y_test ))
Out[11]:TESTING STATS:
classification accuracy: 0.754428341385
confusion matrix:
865 148
157 72
76 5 Supervised Learning
Observe that each time we run the process of randomly splitting the dataset
and train a classifier we obtain a different performance. A good simulation for
approxi- mating the test error is to run this process many times and average the
performances.Let us do this!6
In [12]:
# Spitting done by using the tools provided by sklearn :
from sklearn . c ro ss _va li da tio n import t r a i n _t e s t _ sp l i t
PRC = 0.3
acc = np . zeros ((10 ,) )
for i in xrange (10) :
X_train , X_test , y_train , y_test =
tra in _te st _s pli t ( x , y , t est_size = PRC )
knn = neighbors . KNeighbors Classifier ( n_neighbors = 1)
knn . fit ( X_train , y_train )
yhat = knn . predict ( X_test )
acc [ i] = metrics . accuracy _score ( yhat , y_test )
acc. shape = (1 , 10)
print " Mean expected error :" + str ( np. mean ( acc [0]) )
• In-sample error Ein: The in-sample error or training error is the error
measuredover all the observed data samples in the training set, i.e.,
1 N
E i= i e(x , yi )
n N
i=1
• Out-of-sample error Eout: The out-of-sample error or generalization error mea-
sures the expected error on unseen data. We can approximate/simulate this
quantity by holding back some training data for testing purposes.
Note that the definition of the instantaneous error e(xi , yi ) is still missing. For
example, in classification we could use the indicator function to account for a
cor- rectly classified sample as follows:
1, if h(xi ) = yi
i e(xi , y ) = I [h(ix ) = yi ]=
0 otherwise.
6sklearn allows us to easily automate the train/test splitting using the function
train_test_split(...).
First Steps
77
Observe that:
Eout ≥ Ein
Using the expected error on the test set, we can select the best classifier
for our application. This is called model selection. In this example we cover the
most simplistic setting. Suppose we have a set of different classifiers and want to
select the “best” one. We may use the one that yields the lowest error rate.
In [13]:
What Is Learning?
Let us recall the two basic values defined in the last section. We talk of training error
or in-sample error, Ein, which refers to the error measured over all the observed
datasamples in the training set. We also talk of test error or generalization error,
Eout, as the error expected on unseen data.
We can empirically estimate the generalization error by means of cross-
validationtechniques and observe that:
Eout ≥ Ein.
The goal of learning is to minimize the generalization error; but how can we
guarantee this minimization using only training data?
From the above inequality it is easy to derive a couple of very intuitive ideas.
7The reader should note that there are several bounds in machine learning to characterize the
generalization error. Most of them come from variations of Hoeffding’s inequality.
What Is
Learning? 79
,
log C
E E ≤( C ) + oOut ,
N
where C is a measure of the complexity of the model class we are using. Technically,
we may also refer to this model class as the hypothesis space.
Learning Curves
Let us simulate the effect of the number of examples on the training and test
errorsfor a given complexity. This curve is called the learning curve. We will focus
for amoment in a more simple case. Consider the toy problem in Fig. 5.3.
Let us take a classifier and vary the number of examples we feed it for training
purposes, then check the behavior of the training and test accuracies as the
numberof examples grows. In this particular case, we will be using a decision tree
with fixedmaximum depth.
Observing the plot in Fig. 5.4, we can see that:
• As the number of training samples increases, both errors tend to the same
• value. When we have few training data, the training error is very small but the
test erroris very large.
Now check the learning curve when the degree of complexity is greater in Fig. 5.5.
We simulate this effect by increasing the maximum depth of the tree.
And if we put both curves together, we have the results shown in Fig. 5.6.
Although both show similar behavior, we can note several differences:
80 5 Supervised Learning
Fig. 5.4 Learning curves (training and test errors) for a model with a high degree of complexity
Fig. 5.5 Learning curves (training and test errors) for a model with a low degree of complexity
Fig. 5.6 Learning curves (training and test errors) for models with a low and a high degree of
complexity
Learning
Curves 81
Fig. 5.7 Learning curves (training and test errors) for a fixed number of data samples, as the
complexity of the decision tree increases
• With a low degree of complexity, the training and test errors converge to the
biassooner/with fewer data.
• Moreover, with a low degree of complexity, the error of convergence is larger
thanwith increased complexity.
The value both errors converge towards is also called the bias; and the differ-
ence between this value and the test error is called the variance. The
bias/variance decomposition of the learning curve is an alternative approach to
the training and generalization view.
Let us now plot the learning behavior for a fixed number of examples with
respectto the complexity of the model. We may use the same data but now we
will changethe maximum depth of the decision tree, which governs the complexity
of the model.Observe in Fig. 5.7 that as the complexity increases the training error
is reduced; but above a certain level of complexity, the test error also increases.
This effect is
called overfitting. We may enact several cures for overfitting:
These terms are added to the objective function. They trade off with the error
function in the objective and are governed by a hyperparameter. Thus, we still
have to select this parameter by means of model selection.
• We can use “ensemble techniques”. A third cure for overfitting is to use ensemble
techniques. The best known are bagging and boosting.
Going back to our problem, we have to select a model and control its complexity
according to the number of training data. In order to do this, we can start by
usinga model selection technique. We have seen model selection before when we
wantedto compare the performance of different classifiers. In that case, our best
bet was to select the classifier with the smallest Eout. Analogous to model
selection, we may think of selecting the best hyperparameters as choosing the
classifier with parameters that performs the best. Thus, we may select a set of
hyperparameter values and usecross-validation to select the best configuration.
The process of selecting the best hyperparameters is called validation. This
intro-duces a new set into our simulation scheme; we now need to divide the data
we haveinto three sets: training, validation, and test sets. As we have seen, the
process of assessing the performance of the classifier by estimating the
generalization error is called testing. And the process of selecting a model using
the estimation of the gen-eralization error is called validation. There is a subtle but
critical difference betweenthe two and we have to be aware of it when dealing
with our problem.
• Test data is used exclusively for assessing performance at the end of the
processand will never be used in the learning process.8
• Validation data is used explicitly to select the parameters/models with the best
performance according to an estimation of the generalization error. This is a
formof learning.
• Training data are used to learn the instance of the model from a model class.
.
Training,
Validation and Test 83
In practice, we are just given training data, and in the most general case we
explicitly have to tune some hyperparameter. Thus, how do we select the
different splits?
How we do this will depend on the questions regarding the method that we
wantto answer:
• Let us say that our customer asks us to deliver a classifier for a given problem. If
we just want to provide the best model, then we may use cross-validation on
our training dataset and select the model with the best performance. In this
scenario,when we return the trained classifier to our customer, we know that it
is the one that achieves the best performance. But if the customer asks about
the expected performance, we cannot say anything.
A practical issue: once we have selected the model, we use the complete
trainingset to train the final model.
• If we want to know about the performance of our model, we have to use
unseen data. Thus, we may proceed in the following way:
1. Split the original dataset into training and test data. For example, use 30% of
the original dataset for testing purposes. This data is held back and will only
beused to assess the performance of the method.
2. Use the remaining training data to select the hyperparameters by means of
cross-validation.
3. Train the model with the selected parameter and assess the performance
using the test dataset.
A practical issue: Observe that by splitting the data into three sets, the
classifieris trained with a smaller fraction of the data.
If we want to select the best complexity of a decision tree, we can use tenfold
cross- validation checking for different complexity parameters. If we change the
maximumdepth of the method, we obtain the results in Fig. 5.8.
84 5 Supervised Learning
Fig. 5.8 Box plot showing accuracy for different complexities of the decision tree
Checking Fig. 5.8, we can see that the best average accuracy is obtained by
the fifth model, a maximum depth of 6. Although we can report that the best
accuracy is estimated to be found with a complexity value of 6, we cannot say
anything about the value it will achieve. In order to have an estimation of that
value, we need to runthe model on a new set of data that are completely unseen,
both in training and in model selection (the model selection value is positively
biased). Let us put everything together. We will be considering a simple train_test
split for testing purposes and then run cross-validation for model selection.
In [15]: # Train_test split
X_train , X_test , y_train , y_test = cross_validation
. tra in_ te st _sp li t ( X , y , test_size = 0. 20)
If we run the output of this code, we observe that the best accuracy is
provided by the fourth model. In this example it is a model with complexity 5.9
The selectedmodel achieves a success rate of 0.83423816 in validation. We then
train the modelwith the complete training set and verify its test accuracy.
In [16]: # Train the model with the complete training set with the
selected complexity
dt = tree . Decision Tree Cla ssifier (
min_samp les _l eaf = 1 ,
max_depth = C[ np . argmax ( np. mean ( acc , axis = 0) ) ])
dt . fit ( X_train , y_train )
As expected, the value is slightly reduced; it achieves 0.82608. Finally, the model
is trained with the complete dataset. This will be the model used in exploitation
andwe expect to at least achieve an accuracy rate of 0.82608.
Let us return to our problem and check the performance of different models.
Thereare many learning models in the machine learning literature. However, in
this shortintroduction we focus on two of the most important and pragmatically
effective approaches10: support vector machines (SVM) and random forests (RF).
Before going into some of the details of the models selected, let us check the
com-ponents of any learning algorithm. In order to be able to learn, an algorithm
has to define at least three components:
separating boundary will have a point of a class closer to it than this one. The
figurealso shows the closest points of the classes to the boundary. These points
are calledsupport vectors. In fact, the boundary only depends on those points. If
we remove any other point from the dataset, the boundary remains intact.
However, in general, if any of these special points is removed the boundary will
change.
minimize 1
subject to yi (aT xi + b) ≥ 1, ∀xi ∈ D
The solution of this problem is not unique. Selecting the maximum margin
hyper-plane requires us to add a new constraint to our problem. Remember from
the geom-etry of the hyperplane that the distance of any point to a hyperplane is
T
a x+b
ǁaǁ2
given b y=: d(x,π) .
Recall also that we want positive data to be beyond value 1 and negative data
below −1 . Thus, what is the distance value we want to maximize?
The positive point closest to the boundary is at 1/ǁaǁ2 and the negative point
closest to the boundary data point is also ǁatǁ 1/ a 2. Thus, data points from
differentclasses are aǁt leǁast 2/ a 2 apart.
Recall that our goal is to find the separating hyperplane with maximum
margin, i.e., with maximum distance between elements in the different classes.
Thus, we can complete the former formulation with our last requirement as
follows:
minimize ǁaǁ2/2
subject to yi (aT xi + b) ≥ 1, ∀xi ∈ D
This formulation has a solution as long as the problem is linearly separable.
In order to deal with misclassifications, we are going to introduce a new set of
variables ξi , that represents the amount of violation in the i -th constraint. If the
constraint is already satisfied, then ξ=i 0; while ξi > 0 otherwise. Because ξi is
related to the errors, we would like to keep this amount as close to zero as
possible. This makes us introduce an element in the objective trade-off with the
maximum margin.
12Note the strict inequalities in the formulation. Informally, we can consider the smallest
satisfiedconstraint, and observe that the rest must be satisfied with a larger value. Thus, we can
arbitrarilyset that value to 1 and rewrite the problem as
aT si + b ≥ 1 and aT ri + b ≤ −1.
90 5 Supervised Learning
N
minimize ǁaǁ2/2 + C ξi
i=1
subject to yi (aT xi + b) ≥ 1 − ξi , i = 1 ... N
ξi ≥ 0
where C is the trade-off parameter that roughly balances the rates of margin and
misclassification. This formulation is also called soft-margin SVM.
The larger the C value is, the more importance one gives to the error, i.e., the
method will be more accurate according to the data at hand, at the cost of being
moresensitive to variations of the data.
The decision boundary of most problems cannot be well approximated by a
linearmodel. In SVM, the extension to the nonlinear case is handled by means of
kernel theory. In a pragmatic way, a kernel can be referred to as any function that
captures the similarity between any two samples in the training set. The kernel
has to be a positive semi-definite function as follows:
• Linear kernel:
k(xi , x j ) = x T ix j
• Polynomial kernel:
k(xi , x j ) = (1 + x T xi j )p
• Radial Basis Function kernel:
ǁxi −x j ǁ22σ2
k(xi , x j) = e−
Note that selecting a polynomial or a Radial Basis Function kernel means that
we have to adjust a second parameter p or σ, respectively. As a practical
summary, the SVM method will depend on two parameters (C, γ) that have to be
chosen carefully using cross-validation to obtain the best performance.
Random Forest
Random Forest (RF) is the other technique that is considered in this work. RF is
an ensemble technique. Ensemble techniques rely on combining different
classifiersusing some aggregation technique, such as majority voting. As pointed
out earlier, ensemble techniques usually have good properties for combating
overfitting. In this case, the aggregation of classifiers using a voting technique
reduces the variance of the final classifier. This increases the robustness of the
classifier and usually achievesa very good classification performance. A critical issue
in the ensemble of classifiers is that for the combination to be successful, the
errors made by the members of the ensemble should be as uncorrelated as
possible. This is sometimes referred to in the
literature as the diversity of the classifiers. As the name suggests, the base
classifiersin RF are decision trees.
Tackling the first question leads to different strategies for creating decision tree.
However, most techniques share the axis-orthogonal hyperplane partition policy,
i.e., a threshold in a single feature. For example, in our problem “Does the
applicant have a home mortgage?”. This is the key that allows the results of this
method to be interpreted. In decision trees, the second question is
straightforward, each patch is given the value of a label, e.g., the majority label,
and all data falling in that part ofthe space will be predicted as such.
The RF technique creates different trees over the same training dataset. The
word“random” in RF refers to the fact that only a subset of features is available
to each of the trees in its building process. The two most important parameters in
RF are thenumber of trees in the ensemble and the number of features each tree
is allowed tocheck.
With both techniques in mind, we are going to optimize and check the results
usingnested cross-validation. Scikit-learn allows us to do this easily using several
model selection techniques. We will use a grid search, GridSearchCV (a cross-
validation using an exhaustive search over all combinations of parameters
provided).
92 5 Supervised Learning
The result obtained has a large error in the non-fully funded class (negative).
This is because the default scoring for cross-validation grid-search is mean
accuracy. Depending on our business, this large error in recall for this class may
be unaccept-able. There are different strategies for diminishing the impact of this
effect. On the one hand, we may change the default scoring and find the
parameter setting that cor-responds to the maximum average recall. On the other
hand, we could mitigate thiseffect by imposing a different weight on an error on
the critical class. For example, we could look for the best parameterization such
than one error on the critical class is equivalent to one thousand errors on the
noncritical class. This is important in business scenarios where monetization of
errors can be derived.
Consider that clients using our service yield a profit of 100 units per client (we will use
abstract units but keep in mind that this will usually be accounted in
euros/dollars). We design a campaign with the goal of attracting investors in
order to cover all non-fully funded loans. Let us assume that the cost of the
campaign is α unitsper client. With this policy we expect to keep our customers
satisfied and engaged with our service, so they keep using it. Analyzing the
confusion matrix we can
5.9 A Toy Business Case 93
give precise meaning to different concepts in this campaign. The real positive set
( TP +FN ) consists of the number of clients that are fully funded. According to
our assumption, each of these clients generates a profit of 100 units. The total
profitis· 100 (+T P FN). The campaign to attract investors will be cast considering
all the clients we predict are not fully funded. These are those that the classifier
predict as negative, i . e+. , (FN T N). However, the campaign will only have an
effect on the investors/clients that are actually not funded, i.e., T N ; and we expect
to attract a certain fraction β of them. After deploying our campaign, a simplified
model of theexpected profit is as follows:
100 · ( TP + FN) − α(TN + FN) + 100βTN
When optimizing the classifier for accuracy, we do not consider the business
needs. In this case, optimizing an SVM using cross-validation for different parameters
of the C and γ, we have an accuracy of 85.60% and a confusion matrix with the
followingvalues:
3371. 590.
6. 173.
If we check how the profit changes for different values of α and β, we obtain the
plot in Fig. 5.10. The figure shows two hyperplanes. The horizontal plane is the
expected profit if the campaign is not launch·ed, i.e+., 100 ( TP FN). The other
hyperplanerepresents the profit of the campaign for different values of α and β using
a particular classifier. Remember that the cost of the campaign is given by α, and the
success rate of the campaign is represented by β. For the campaign to be
successful we would like to select values for both parameters so that the profit of
the campaign is larger than the cost of launching it. Observe in the figure that
certain costs and attraction rates result in losses.
We may launch different classifiers with different configurations and toy with dif-
ferent weights (2, 4, 8, 16) for elements of different classes in order to bias the classi
Supervised Learning
Fig. 5.11 3D surfaces of the profit obtained for different classifiers and configurations of retention
campaign cost and retention rate. a RF, b SVM with the same cost per class, c SVM with double
cost for the target class, d SVM with a cost for the target class equal to 4, e SVM with a cost for
the target class equal to 8, f SVM with a cost for the target class equal to 16
fier towards obtaining different values for the confusion matrix.13 The weights define
Table 5.1 Different configurations of classifiers and their respective profit rates and accuracies
Max profit rate (%) Profit rate at 60% (%) Accuracy (%)
Random forest 4.41 2.41 87.87
SVM {1 : 1} 4.59 2.54 85.60
SVM {1 : 2} 4.52 2.50 85.60
SVM {1 : 4} 4.30 2.28 83.81
SVM {1 : 8} 10.69 3.57 52.51
SVM {1 : 16} 10.68 2.88 41.40
Checking the values in Fig. 5.11, we find the results collected in Table 5.1. Observe
that the most profitable campaign with 60% corresponds to a classifier that considers
the cost of mistaking a sample from the non-fully funded class eight times larger
than the one from the other class. Observe also that the accuracy in that case is
muchworse than in other configurations.
The take-home idea of this section is that business needs are often not aligned
with the notion of accuracy. In such scenarios, the confusion matrix values have
specificmeanings. This must be taken into account when tuning the classifier.
96 5 Supervised Learning
may tackle many more different settings. For example, we may have different
targetlabels for a single example; this is called multilabel learning. Or, data can
come from streams or be time dependent; in these settings, sequential learning or
sequence learning can be the methods of choice. Moreover, each data example
can be a non-vector or have a variable size, such as a graph, a tree, or a string. In
such scenarios kernel learning or structural learning may be used. During these last
years we are also seeing the revival of neural networks under the name of deep
learning and achieving impressive results in different domains such as computer
vision or natural languageprocessing. Nonetheless, all of these methods will behave
as explained in this chapter and most of the lessons learned here can be readily
applied to these techniques.
UNIT-4
Regression analysis, Regression: linear regression simple linear regression,
multiple & Polynomial regression, Sparse model. Unsupervised learning,
clustering, similarity and distances, quality measures of clustering, case
study.
Regression Analysis
Introduction
Fig. 6.1 Illustration of different simple linear regression models. Blue points correspond to a set
of random points sampled from a univariate normal (Gaussian) distribution. Red, green and
yellow lines are three different simple linear regression models
Linear Regression
best model (best parameters) for this particular set of samples? See the three
different models (straight lines in different colors) in Fig. 6.1.
Ordinary least squares (OLS) is the simplest and most common estimator in which
the parameters (a’s) are chosen to minimize the square of the distance between
thepredicted values and the actual values with respect to a0,a1:
n
||a0 + a1x − y|2|2 = (a0 + a1x j − y j )2.
j=1
We are concerned here with the y-axis distance, since it does not consider the
error in the variables. This error expression is often called the sum of squared
errors of prediction (SSE). The SSE function is quadratic in the parameters, w, with
positive- definite Hessian, and therefore this function possesses a unique global
m̂ in=imˆum ˆat w (a0, a1). The resulting model is representeˆd =asˆfo+lloˆws: y a0
a1x, where the hats on the variables represent the fact that they are estimated
from the data available.
OLS is a popular approach for several reasons. It makes it computationally cheap to
calculate the coefficients. It is also easier to interpret than the other more
sophisticated models. In situations where the goal is to understand a simple model
in detail, ratherthan to estimate the response well, it can provide insight into what
the model captures. Finally, in situations where there is a lot of noise, as in many
real scenarios, it maybe hard to find the true functional form, so a constrained
model can perform quite well compared to a complex model which can be more
affected by noise.
Practical Case: Sea Ice Data and Climate Change
In this practical case, we pose the question: Is the climate really changing? More
concretely, we want to show the effect of the climate change by determining whether
the sea ice area (or extent) has decreased over the years. Sea ice area refers to
the total area covered by ice, whereas sea ice extent is the area of ocean with at
least 15% sea ice. Reliable measurement of sea ice edges began with the satellite
era in the late 1970s. Before then, sea ice area and extent were monitored less
precisely bya combination of ships, buoys, and aircraft.
We will use the sea ice data from the National Snow & Ice Data Center 1 which
provides measurements of the area and extend of sea ice at the poles over the
last 36 years. The center has given access to the archived monthly Sea Ice Index
imagesand data since 1979 [2]. The archived data reside at an FTP location2 (web-
page instructions can be followed easily to access and download the files). Th e
ASCII data files tabulate sea ice extent and area (in millions of square kilometers )
by yearfor a given month.
In order to check whether there is an anomaly in the evolution of sea ice
extent over recent years, we want to build a simple linear regression model and
analyze thefitting; but before we need to perform several processing steps.
.
1
0 ession Analysis
0
Fig. 6.2 Ice extent data by month
6
In[1]:
R
e First, we read the data, previously downloaded, and create a DataFrame
(gPandas) as follows:
delim_whitespace = True )
p r i nt ’ shape : ’, i ce . shape
Next, we visualize the data. The lmplot() function from the Seaborn toolboxis
intended for exploring linear relationships of different forms in multidimensional
datasets. For instance, we can illustrate the relationship between the month of the
year (variable) and the extent(response) as follows:
In[3]:
import Seaborn as sns
This outputs Fig. 6.2. We can observe a monthly fluctuation of the sea ice
extent,as would be expected for the different seasons of the year.
We should normalize the data before performing the regression analysis to
avoid this fluctuation and be able to study the evolution of the extent over the
years. To capture the variation for a given interval of time (month), we can
compute the mean
Fig. 6.3 Ice extent data by month after the normalization
for the i-th interval of time (using the period from 1979 through 2014 for the
{ oj}nth ei .
meanextent) μi , and subtract it from the set of extent values for that m
This value can be converted to a relative percentage difference by dividing it by
the totalaverage (1979–2014) μ, and then multiplying by 100:
ei − μi
i j
je˜ = 100 ∗ , i = 1, . . . , 12.
μ
We implement this normalization and plot the relationship again as follows:
In[4]:
for i in range (1 2 ) :
ic e 2 . extent [ ice2 . mo == i + 1 ] =
The new output is in Fig. 6.3. We now observe a comparable range of values
forall months.
Next, the normalized values can be plotted for the entire time series to analyze the
tendency. We compute the trend as a simple linear regression. We use the lmplot()
function for visualizing linear relationships between the year (variable) and the extent
(response).
In[5]:
This outputs Fig. 6.4 showing the regression model fitting the extent data.
This plot has two main components. The first is a scatter plot, showing the
observed data points. The second is a regression line, showing the estimated
linear model relating
Fig. 6.4 Regression model fitting sea ice extent data for all months by year using lmplot
the two variables. The regression line is plotted with a 95% confidence band to
givean impression of the uncertainty in the model.
In this figure, we can observe that the data show a long-term negative trend
overyears. The negative trend can be attributed to global warming, although there
is alsoa considerable amount of variation from year to year.
Up until here, we have qualitatively shown the linear regression using a useful
visu- alization tool. We can also analyze the linear relationship in the data using the
Scikit- learn library, which allows a quantitative evaluation. As was explained in the
previous chapter, Scikit-learn provides an object-oriented interface centered
around the con-cept of an estimator. The sklearn.linear_model.LinearRegression
estimator sets the state of the estimator based on the training data using the
function fit. Moreover, it allows the user to specify whether to fit an intercept
term in the object construction. This is done by setting the corresponding
constructor argumentsof the estimator object as follows:
from sklearn . linear_model import Li ne ar Re g re s si on
In[6]:
est = L i ne ar R eg re s si on ( fit_intercept = True )
During the fitting process, the state of the estimator is stored in instance
attributes that have a trailing underscore (‘_’). For example, the coefficients of a
LinearRegression estimator are stored in the attribute coef_. We fit a regres- sion
model using years as variables (x) and the extent values as the response (y).
In[7]:
x = i c e2 [[ ’ year ’ ]]
y = ice2 [[ ’ e x t e n t ’ ]]
est . fi t ( x , y)
print " Coefficients :" , est . coef_
6.2 Linear Regression 103
Out[9]: Prediction of extent for January 2025 (in millions of squarekm): [12.93603933].
Sparse Model
Often, in real problems, there are uninformative variables in the data which
prevent proper modeling of the problem and thus, the building of a correct
regression model. In such cases, a feature selection process is crucial to select
only the informative features and discard non-informative ones. This can be
achieved by sparse methods which use a penalization approach, such as LASSO
(least absolute shrinkage and selection operator) to set some model coefficients
to zero (thereby discarding thosevariables). Sparsity can be seen as an application
of Occam’s razor: prefer simpler models to complex ones.
Given the set of samples (X, y), the objective of a sparse model is to minimize
the SSE through a restriction (or penalty):
1
||Xw − y||2 + α||w|| ,
1
2
2n
where ||w||1 is the L1-norm of the parameter vector w = (a 0 , .. ., ad ).
Practical Case: Prediction of the Price of a New Housing Market
In this practical case we want to solve the question: Can we predict the price of a
new market given any of its attributes?
We will use the Boston housing dataset from Scikit-learn, which provides recorded
measurements of 13 attributes of housing markets around Boston, as well as the
median house price.3 Once we load the dataset (506 instances), the description
of the dataset can easily be shown by printing the field DESCR. The data (x),
feature names, and target (y) are stored in other fields of the dataset.
We first consider the task of predicting median house values in the Boston
area using as the variable one of the attributes, for instance, LSTAT, defined as the
“pro-portion of lower status of the population”.
Seaborn visualization can be used to show this linear relationships easily:
Fig. 6.5 Scatter plot of Boston data (LSTATversus price) and their linear relationship (using
lmplot)
To study the relation among multiple variables in a dataset, there are different
options. We can study the relationship between several variables in a dataset by
using the functions corr and heatmap which allow to calculate a correlation matrix
for a dataset and draws a heat map with the correlation values. The heat mapis a
matricial image which helps to interpret the correlations among variables. For the
sake of visualization, we do not consider all the 13 variables in the Boston
housing data, but six: CRIM, per capita crime rate by town; INDUS, proportion of
non-retail
106 6 Regression Analysis
Fig. 6.6 Scatter plot of Boston data (LSTAT versus price) and their polynomial relationship(using
lmplotwith order 2)
business acres per town; NOX, nitric oxide concentrations (parts per 10 million);
RM,average number of rooms per dwelling; AGE, proportion of owner-occupied
units built prior to 1940; and LSTAT. These variables are indicated by their indexes
in thefollowing code:
Figure 6.7 shows a heat map representing the correlation between pairs of vari-
ables; specifically, the six variables selected and the price of houses. The color
bar shows the range of values used in the matrix. This plot is a useful way of
summa- rizing the correlation of several variables. It can be seen that LSTAT and RM
are the variables that are most correlated with price.
Another good way to explore multiple variables is the scatter plot from
Pandas. The scatter plot is a grid of plots of multiple variables one against the
others, illus-trating the relationship of each variable with the rest. For the sake of
visualization,we do not consider all the variables, but just three: RM, AGE, and LSTAT
defined by indexesin the following code:
In [13]:
df 2 = pd . Data Frame ( boston . data [: , indexes ],
columns = boston . feature_names [ indexes ])
df2 [ ’ price ’] = boston . target
pd . scatter_matrix ( df2 , figsize = (12.0 , 12. 0) )
6.2 Linear Regression 107
This code outputs Fig. 6.8, where we obtain visual information concerning the
density function for every variable, in the diagonal, as well as the scatter plots of
the data points for pairs of variables. In the last column, we can appreciate the
relationbetween the three variables selected and house prices. It can be seen that
RMfollowsa linear relation with price; whereas AGE does not. LSTAT follows a higher-
order relation with price. This plot gives us an indication of how good or bad
every attribute would be as a variable in a linear model.
For the evaluation of the prediction power of the model with new samples, we
split the data into a training set and a testing set, and we compute the linear
regression score, which returns the coefficient of determination R2 of the
prediction. We can also calculate the MSE.
In [14]: from sklearn import linear_model
train_size = X_boston . shape [ 0]/ 2
X_train = X_boston [: train_size ]
X_test = X_boston [ train_size :]
y_train = y_boston [: train_size ]
y_test = y_boston [ train_size :]
print ’ Training and testing set sizes ’,
X_train . shape , X_test . shape
regr = Linear Regr ess io n ()
regr . fit ( X_train , y_train )
print ’ Coeff and intercept : ’,
regr . coef_ , regr . intercept_
print ’ Testing Score : ’, regr . score ( X_test , y_test ) print ’
Training
MSE : ’,
np . mean (( regr . predict ( X_train ) - y_train ) **2)
print ’ Testing MSE : ’,
np . mean (( regr . predict ( X_test ) - y_test ) ** 2)
108 6 Regression Analysis
Out[16]: Ordered variable (from less to more important): [’CRIM’ ’INDUS’ ’CHAS’ ’NOX’ ’TAX’ ’B’ ’ZN’ ’AGE’
’RAD’ ’LSTAT’ ’PTRATIO’ ’DIS’’RM’]
There are also other strategies for feature selection. For instance, we can
select=the k 5 best features, according to the k highest scores, using the function
SelectKBestfrom Scikit-learn:
In [17]: import sklearn . fe at ure _s e lec ti on as fs
selector = fs . Select KBest ( score_func = fs . f_regression ,
k = 5)
selector . fit_transform ( X_train , y_train ) per
selector . fit ( X_train , y_train )
print ’ Selected features : ’,
zip ( selector . get_support () , boston . feature_names )
Fig. 6.9 Relation between true (x-axis) and predicted (y-axis) prices
The output is shown in Fig. 6.9, where we can observe that the original
prices are properly estimated by the predicted ones, except for the higher
values, around
$50.000 (points in the top right corner).
Finally, it is worth noting that we can work with statistical evaluation of a
linearregression with the OLS toolbox of the Stats Model toolbox.4 This toolbox is
useful to study several statistics concerning the regression model. To know more
about thetoolbox, go to the Documentation related to Stats Models.
Logistic Regression
Regression 111
Fig. 6.11 Linear regression (blue) versus logistic regression (red) for fitting a set of data (black points)
normally distributed across the 0 and 1 y-values
Figure 6.10 illustrates the logistic function with different values of λ. This function
is useful because it can take as its input any value from negative infinity to
positive infinity, whereas the output is restricted to values between 0 and 1 and
hence can beinterpreted as a probability.
The set of samples (X, y), illustrated as black points in Fig. 6.11, defines a fitting
problem suitable for a logistic regression. The blue and red lines show the fitting
result for linear and logistic models, respectively. In this case, a logistic model can
clearly explain the data; whereas a linear model cannot.
Practical Case: Winning or Losing Football Team
Now, we pose the question: What number of goals makes a football team the
winneror the loser? More concretely, we want to predict victory or defeat in a
football match when we are given the number of goals a team scores. To do this
we consider
the set of results of the football matches from the Spanish league5 and we build a
classification model with it.
We first read the data file in a DataFrame and select the following columnsin
a new DataFrame: HomeTeam, AwayTeam, FTHG(home team goals), FTAG(away
team goals), and FTR (H=home win, D d r a w=, A awa=y win). We then build a d-
dimensional vector of variables with all the scores, x, and a binary response
indicating victory or defeat, y. For that, we create two extra columns containing
Wthe number of goals of the winning team and L the number of goals of the losing
team and we concatenate these data. Finally, we can compute and visualize a logistic
regression model to predict the discrete value (victory or defeat) using these
data.
In [19]: from sklearn . li near_model import Lo gistic Regression data = pd.r ead_csv( ’
files /ch06/SP1.csv’)
s = data[[’Home Team’,’Away Team’, ’FTHG’, ’FTAG’, ’FTR’]]def my_f1(row):
return max(row[’FTHG’], row[’FTAG’])def my_f2(row):
return min(row[’FTHG’], row[’FTAG’]) s[’W’] = s.appl y(
my_f1, axis = 1)
s[’L’] = s.a pply(my_f2, axis = 1)x1 = s[’W’].val ues
y1 = np.ones(len(x1), dtype = np.int)x2 = s[’L’].valu es
y2 = np.zeros(len(x2), dtype = np.int)x = np.c oncate nate
([x1, x2])
x = x[:, np.n ewaxis]
y = np.c oncatenate([y1, y2]) logreg =
Logisti c R egr essio n ()l ogreg.fit(x, y)
X_test = np.l inspace(-5, 10, 300)def l r_model( x ) :
return 1 / (1+np.exp( - x))
loss = l r_model(X_test*logreg.coef_ + logreg.intercept_)
.ravel()
X_test 2 = X_test[:,np.newaxis ]
losspred = logreg.p redict(X_test 2 )plt.s catter(x.ravel
(), y,
color = ’black’,
s = 100, zorder = 20,
alpha = 0.03)
plt.plot(X _test, loss, color = ’blue’, l in ewi dth = 3)
plt.plot(X _test, losspred, color = ’red’, l in ewidt h = 3)
Figure 6.12 shows a scatter plot with transparency so we can appreciate the over-
lapping in the discrete positions of the total numbers of victories and defeats. It
also shows the fitting of the logistic regression model, in blue, and prediction of
thelogistic regression model, in red, for the Spanish football league results. With
this information we can estimate that the cutoff value is 1. This means that a
team, in general, has to score more than one goal to win.
5http://www.football-data.co.uk/mmz4281/1213/SP1.csv.
Fig. 6.12 Fitting of the logistic regression model (blue) and prediction of the logistic regression model
(red) for the Spanish football league results
Unsupervised Learning
Introduction
• Examples within a cluster are similar (in this case, we speak of high intraclass
similarity).
• Examples in different clusters are different (in this case, we speak of low interclass
similarity).
When we denote data as similar and dissimilar, we should define a measure for
this similarity/dissimilarity. Note that grouping similar data together can help in
discov- ering new categories in an unsupervised manner, even when no sample
category labels are provided. Moreover, two kinds of inputs can be used for
grouping:
• What is a natural grouping among the objects? We need to define the “groupness”
and the “similarity/distance” between data.
• How can we group samples? What are the best procedures? Are they efficient?
Are they fast? Are they deterministic?
• How many clusters should we look for in the data? Shall we state this
numbera priori? Should the process be completely data driven or can the user
guide the grouping process? How can we avoid “trivial” clusters? Should we
allow final clustering results to have very large or very small clusters? Which
methods work when the number of samples is large? Which methods work
when the number ofclasses is large?
• What constitutes a good grouping? What objective measures can be defined to
evaluate the quality of the clusters?
To speak of similar and dissimilar data, we need to introduce a notion of the similarity
of data. There are several ways for modeling of similarity. A simple way to model
this is by means of a Gaussian kernel:
s(a, b) = e−γd(a,b)
where d(a, b) is a metric function, and γ is a constant that controls the decay of the
function. Observe that when a=b, the similarity is maximum and equal to one. On
the contrary, when a is very different to b, the similarity tends to zero. The
former modeling of the similarity function suggests that we can use the notion of
distance as a surrogate. The most widespread distance metric is the Minkowski
distance:
d
d(a, b) = ( |ai − bi|p)1/p
i=1
where d(a, b) stands for the distance between two elements a, b∈ Rd , d is the
dimensionality of the data, and p is a parameter.
The best-known instantiations of this metric are as follows:
• a is the number of pairs of elements in S that are in the same subset in both X and
Y;
• b is the number of pairs of elements in S that are in different subsets in both X and
Y;
• c is the number of pairs of elements in S that are in the same subset in X , but
indifferent subsets in Y ; and
• d is the number of pairs of elements in S that are in different subsets in X , but
inthe same subset in Y .
Another way for comparing clustering results is the V-measure. Let us first intro-
duce some concepts. We say that a clustering result satisfies a homogeneity
criterion if all of its clusters contain only data points which are members of the
same original(single) class. A clustering result satisfies a completeness criterion if
all the data points that are members of a given class are elements of the same
predicted cluster. Note that both scores have real positive values between 0.0
In[1]:
and 1.0, larger values being desirable. For example, if we consider two toy
print (" %.3 f" % metrics . homog en eit y_ sc ore ([0 , 0 , 1 , 1] ,
clustering sets (e.g., original and predicted) with four s[ a0 m, p0le,s a0n,d 0t]w)o) labels, we
get:
Out[1]: 0.000
.
7.2 Clustering 119
Out[3]: 0.000
In contrast, clusters that include samples from different classes destroy the
homo-geneity of the labeling, hence:
In [4]: print (" %.3 f" % metrics . v_mea su re_ sc or e ([0 , 0 , 1 , 1] ,
[0 , 0 , 0 , 0]) )
Out[4]: 0.000
In summary, we can say that the advantages of the V-measure include that it
has bounded scores: 0.0 means the clustering is extremely bad; 1.0 indicates a
per-fect clustering result. Moreover, it can be interpreted easily: when analyzing
the V-measure, low completeness or homogeneity explain in which direction the
clus- tering is not performing well. Furthermore, we do not assume anything
about the cluster structure. Therefore, it can be used to compare clustering
algorithms suchas K-means, which assume isotropic blob shapes, with results of
other clustering algorithms such as spectral clustering (see Sect. 7.2.3.2), which can
find clusters with “folded” shapes. As a drawback, the previously introduced
metrics are not normalized with regard to random labeling. This means that
depending on the num- ber of samples, clusters and groundtruth classes, a
completely random labeling will
120 7 Unsupervised Learning
not always yield the same values for homogeneity, completeness and hence, the
V- measure. In particular, random labeling will not yield a zero score, and they will
tend further from zero as the number of clusters increases. It can be shown that
this prob-lem can reliably be overcome when the number of samples is high, i.e.,
more than athousand, and the number of clusters is less than 10. These metrics
require knowl- edge of the groundtruth classes, while in practice this information
is almost never available or requires manual assignment by human annotators.
Instead, as mentioned before, these metrics can be used to compare the results of
different clusterings.
Silhouette Score
An alternative to the former scores is to evaluate the final ‘shape’ of the
clustering result. This is the underlying idea behind the Silhouette coefficient. It is
defined asa function of the intracluster distance of a sample in the dataset, a and
the nearest- cluster distance, b for each sample.2 Later, we will discuss different
ways to compute the distance between clusters. The Silhouette coefficient for a
sample i can be written as follows: b −a
Silhouette(i= ) .
max(a, b)
Hence, if the Silhouette s(i) is close to 0, it means that the sample is on the border
ofits cluster and the closest one from the rest of the dataset clusters. A negative
valuemeans that the sample is closer to the neighbor cluster. The average of the
Silhouettecoefficients of all samples of a given cluster defines the “goodness” of
the cluster. A high positive value, i.e., close to 1 would mean a compact cluster,
and vice versa. And the average of the Silhouette coefficients of all clusters gives
idea of the quality of the clustering result. Note that the Silhouette coefficient
only makes sense whenthe number of labels predicted is less than the number of
samples clustered.
The advantage of the Silhouette coefficient is that it is bounded between− 1 and
+1. Moreover, it is easy to show that the score is higher when clusters are dense
and well separated; a logical feature when speaking about clusters. Furthermore,
theSilhouette coefficient is generally higher when clusters are compact.
Within different clustering algorithms, one can find soft partition algorithms,
which assign a probability of the data belonging to each cluster, and also hard
partition algorithms, where each datapoint is assigned precise membership of
one cluster. A typical example of a soft partition algorithm is the Mixture of
Gaussians [1], which can be viewed as a density estimator method that assigns
a confidence or
2The intracluster distance of sample i is obtained by the distance of the sample to the nearest sample
from the same class, and the nearest-cluster distance is given by the distance to the closest
samplefrom the cluster nearest to the cluster of sample i.
probability to each point in the space. A Gaussian mixture model is a probabilistic
model that assumes all the data points are generated from a mixture of a finite
number of Gaussian distributions with unknown parameters. The universally
used generative unsupervised clustering using a Gaussian mixture model is also
known as EM Clustering. Each point in the dataset has a soft assignment to the K
clusters. One can convert this soft probabilistic assignment into membership by
picking out the most likely clusters (those with the highest probability of
assignment).
An alternative to soft algorithms are the hard partition algorithms, which assign a
unique cluster value to each element in the feature space. According to the
grouping process of the hard partition algorithm, there are two large families of
clustering techniques:
K-means Clustering
K-means algorithm is a hard partition algorithm with the goal of assigning each
datapoint to a single cluster. K-means algorithm divides a set of n samples X into
k disjoint clusters ci, i =1 , . , k, each described by the mean μi of the samples in the
cluster. The means are commonly called cluster centroids. The K-means algorithm
assumes that all k groups have equal variance.
K-means clustering solves the following minimization problem:
k k
where ci is the set of points that belong to cluster i and μi is the center of the
class ci. K-means clustering objective function uses the square of the Euclidean
di stance d=(x|,|μ j−
) x μ|j|2, that is also referred to as the inertia or within-cluster sum-
of-squares. This problem is not trivial to solve (in fact, it is NP-hard problem), so
the algorithm only hopes to find the global minimum, but may become stuck at a
different solution.
In other words, we may wonder whether the centroids should belong to the
original set of points:
n
inertia = minμj∈c(||xi − μj||2)). (7.2)
i=0
122 7 Unsupervised Learning
Let us illustrate the algorithm in Python. First, we will create three sample
distri-butions:
In[5]:
MAXN = 40
X = np . c o n c a t e n a t e ([
1.25 * np . random . randn ( MAXN , 2) ,
5 + 1 .5 * np . r a n d o m . randn ( MAXN , 2) ])
X = np . c o n c a t e n a t e ([
X , [8 , 3] + 1 .2 * np . random . randn ( MAXN , 2) ])
The sample distributions generated are shown in Fig. 7.1 (left). However, the algo-
rithm is not aware of their distribution. Figure 7.1 (right) shows what the
algorithm sees. Let us assume that we expect to have three=clusters (k 3) and
apply the K-means command from the Scikit-learn library:
Fig. 7.1 Initial samples as generated (left), and samples seen by the algorithm (right)
7.2 Clustering 123
• The inertia assumes that clusters are isotropic and convex, since the Euclidean
distance is applied, which is isotropic with regard to the different dimensions
of the data. However, we cannot expect that the data fulfill this assumpti on by
default. Hence, the K-means algorithm responds poorly to elongated clusters or
manifoldswith irregular shapes.
• The algorithm may not ensure convergence to the global minimum. It can be
shown that K-means will always converge to a local minimum of the inertia
(Eq. (7.2)). It depends on the random initialization of the seeds, but some
seeds can result in a poor convergence rate, or convergence to suboptimal
clustering. To alleviate the problem of local minima, the K-means computation
is often per- formed several times, with different centroid initializations. One
way to address this issue is the k-means++initialization scheme, which has been
implemented in Scikit-learn (use the init=’kmeans++’ parameter). This parameter
initializes the centroids to be (generally) far from each other, thereby probably
leading to better results than random initialization.
• This algorithm requires the number of clusters to be specified. Different
heuristics can be applied to predetermine the number of seeds of the
algorithm.
• It scales well to a large number of samples and has been used across a large
rangeof application areas in many different fields.
In summary, we can conclude that K-means has the advantages of allowing the
easy use of heuristics to select good seeds; initialization of seeds by other
methods;multiple points to be tried. However, in contrast, it still cannot ensure
that the localminima problem is overcome; it is iterative and hence slow when
there are a lot of high-dimensional samples; and it tends to look for spherical
clusters.
Spectral Clustering
Up to this point, the clustering procedure has been considered as a way to find
datagroups following a notion of compactness. Another way of looking at what a
clusteris is provided by connectivity (or similarity). Spectral clustering [2] refers to a
familyof methods that use spectral techniques. Specifically, these techniques are
related tothe eigendecomposition of an affinity or similarity matrix and solve the
problem of clustering according to the connectivity of the data. Let us consider an
ideal similarity matrix of two clear sets.
Let us denote the similarity matrix, S, as the matrix S=ij s(xi, xj) which gives the
similarity between observations xi and xj. Remember that we can model
similarity
using the Euclidean distance, d(xi, xj) = ||xi − xj||2, by means of a Gaussian Kernel
as follows:
s(xi, xj) = exp(−α||xi − xj||2),
where α is a parameter. We expect two points from different clusters to be far
awayfrom each other. However, if there is a sequence of points within the cluster
that forms a “path” between them, this also would lead to big distance among some
of the points from the same cluster. Hence, we define an affinity matrix A based on
the similaritymatrix S, where A contains positive values and is symmetric. This can
be done, for example, by applying a k-nearest neighbor that builds a graph
connecting just thek closest data points. The symmetry comes from the fact that
Aij and Aji give the distance between the same points. Considering the affinity
matrix, the clustering can be seen as a graph partition problem, where connected
graph components correspond to clusters. The graph obtained by spectral clustering
will be partitioned so that graph edges connecting different clusters have low
weights, and vice versa. Furthermore, we define a degree matrix D, where each
diagonal value is th e =de g r−
ee of the respective graph node and all other elements
are 0. Finally, we can compute the unnormalizedgraph Laplacian (U D A) and/or a
normalized version of the Laplacian (L), as follows:
the transition matrix. Spectral clustering obtains groups of nodes such that the
random walk corresponds to seldom transitions from one group to another.
−1 1
• Normalized Laplacian: L = D U D2 . 2
−
If we assume that there are k clusters, the next step is to find the k
small-est eigenvectors, without considering the trivial constant eigenvector. Each
row of the matrix formed by the k smallest eigenvectors of the Laplacian matrix
defines a transformation of the data xi. Thus, in this transformed space, we can
apply K-means clustering in order to find the final clusters. If we do not know in
advancethe number of clusters, k, we can look for sudden changes in the sorted
eigenvaluesof the matrix, U , and keep the smallest ones.
Hierarchical Clustering
Another well-known clustering technique of particular interest is hierarchical cluster-
ing. Hierarchical clustering is comprised of a general family of clustering algorithms
that construct nested clusters by successive merging or splitting of data. The hier-
archy of clusters is represented as a tree. The tree is usually called a dendrogram.
The root of the dendrogram is the single cluster that contains all the samples; the
leaves are the clusters containing only one sample each. This is a nice tool,
since it can be straightforwardly interpreted: it “explains” how clusters are
formed and visualizes clusters at different scales. The tree that results from the
technique shows
the similarity between the samples. Partitioning is computed by selecting a cut
onthe tree at a certain level.
In general, there are two types of hierarchical clustering:
When merging two clusters, a question naturally arises: How to measure the
similarity of two clusters? There are different ways to define this with different
results for the agglomerative clustering. The linkage criterion determines the
metricused for the cluster merging strategy:
Let us illustrate how the different linkages work with an example. Let us
generatethree clusters as follows:
In [8]:
MAXN1 = 500
MAXN2 = 400
MAXN3 = 300
X1 = np . c o n c a t e n a t e ([
2. 2 5 * np . random . r a nd n ( MA XN 1 , 2) ,
4 + 1.7* np . r a n d o m . randn ( MA XN2 , 2) ])
X1 = np . c o n c a t e n a t e ([
X1 , [8 , 3] + 1.9* np . random . randn ( M AX N3 , 2) ])
y1 = np . c o n c a t e n a t e ([
2 * np . ones (( M AX N2 , 1) ) ])
y1 = np . c o n c a t e n a t e ([
y1 , 3 * np . o n es (( M AXN 3 , 1) ) ]) . ravel ()
y1 = np . int_ ( y1 )
l a b e l s _ y 1 = [ ’+ ’, ’* ’, ’o ’]
colors = [ ’r ’, ’g ’, ’b ’]
plt . show ()
The results of the agglomerative clustering using the different linkages: complete,
average, and Ward are given in Fig. 7.3. Note that agglomerative clustering
exhibits “rich get richer” behavior that can sometimes lead to uneven cluster
sizes, with average linkage being the worst strategy in this respect and Ward
linkage giving themost regular sizes. Ward linkage is an attempt to form clusters
that are as compactas possible, since it considers inter- and intra-distances of the
clusters. Meanwhile, for non-Euclidean metrics, average linkage is a good
alternative. Average linkage can produce very unbalanced clusters, it can even
separate a single data point into aseparate cluster. This fact would be useful if we
want to detect outliers, but it may be undesirable when two clusters are very
close to each other, since it would tend tomerge them.
Agglomerative clustering can scale to a large number of samples when it is
usedjointly with a connectivity matrix, but it is computationally expensive when no
con-
nectivity constraints are added between samples: it considers all the possible
mergesat each step.
Fig. 7.3 Illustration of agglomerative clustering using different linkages: Ward, complete, and
average. The symbol of each data point corresponds to the original class generated and the
color corresponds to the cluster obtained
Fig. 7.4 Illustration of agglomerative clustering without (top row) and with (bottom row) a connec-
tivity graph using the three linkages (from left to right): average, complete, and Ward. The
colorscorrespond to the clusters obtained
Fig. 7.5 Comparison of the different clustering techniques (from left to right): K-means, spectral
clustering, and agglomerative clustering with average and Ward linkage on simple compact datasets.
In the first row, the expected number of clusters is k = 2 and in the second row: k = 4
Comparison of Different Hard Partition Clustering Algorithms Let us
compare the behavior of the different clustering algorithms discussed so far.For
this purpose, we generate three different datasets’ configurations:
Fig. 7.6 Comparison of the different clustering techniques (from left to right): K-means, spectral
clustering, and agglomerative clustering with average and Ward linkage on uniformly
distributeddata. In the first row, the number of clusters assumed is k = 2 and in the second row:
k =4
Fig. 7.7 Comparison of the different clustering techniques (from left to right): K-means, spec-
tral clustering, and agglomerative clustering with average and Ward linkage on non-flat
geometry datasets. In the first row, the expected number of clusters is k = 2 and in the second
row: k = 4
second cluster of a small set of data. This behavior is observed in both cases: k= 2
and k = 4.
Regarding datasets with more complex geometry, like in the moon dataset
(see Fig. 7.7), K-means and Ward linkage agglomerative clustering attempt to
construct compact clusters and thus cannot separate the moons. Due to the
connectivity con- straint, the spectral clustering and the average linkage
agglomerative clustering sep-ar a= t e d both moons in case =o f k 2, while in case of k
4, the average linkage agglomerative clustering clustered most of datasets
correctly separating some of thenoisy data points as two separate single clusters.
In the case of spectral clustering, looking for four clusters, the method splits each
of the two moon datasets into two clusters.
132 7 Unsupervised Learning
Fig. 7.8 Expenditure on different educational indicators for the first five countries in the Eurostat
dataset
Case Study
In order to illustrate clustering with a real dataset, we will now analyze the indicators
of spending on education among the European Union member states, provided
by the Eurostat data bank.3 The data are organized by year (TIME) from 2002
until 2011 and country (GEO): (‘Albania’, ‘Austria’, ‘Belgium’, ‘Bulgaria’, etc.).
Twelveindicators (INDIC_ED) of financing of education with their corresponding
values (Value) are given: (1) Expenditure on educational institutions from private
sources as % of gross domestic product (GDP), for all levels of education
combined; (2) Expenditure on educational institutions from public sources as %
of GDP, for all levels of government combined, (3) Expenditure on educational
institutions from public sources as % of total public expenditure, for all levels of
education combined,
(4) Public subsidies to the private sector as % of GDP, for all levels of education
combined, (5) Public subsidies to the private sector as % of total public
expenditure, for all levels of education combined, etc. We can store the 12
indicators for a givenyear (e.g., 2010) in a table. Figure 7.8 provides visualization of
the first five countries in the table.
As we can observe, this is not a clean dataset, since there are values missing.
Somecountries have very limited information and should be excluded. Other
countries maystill not collect or have access to a few indicators. For these last cases,
we can proceedin two ways: (a) fill in the gaps with some non-informative, non-
biasing data; or (b)drop the features with missing values for the analysis. If we
have many features andonly a few have missing values, then it is not very harmful
to drop them. However, ifmissing values are spread across most of the features, we
eventually have to deal withthem. In our case, both options seem reasonable, as
long as the number of missingfeatures for a country is not too large. We will
proceed in both ways at the same time.We apply both options: filling the gap
with the mean value of the feature and the dropping option, ignoring the
indicators with missing values. Let us now applyK-means clustering to thesedatin
order to partition the countries according to
.
7.3 Case Study 133
Fig. 7.9 Clustering of the countries according to their educational expenditure using filled-in (top
row) and dropped (bottom row) missing values
their investment in education and check their profiles. Figure 7.9 shows the
results of this K-means clustering. We have sorted the data for better
visualization. Ata simple glance, we can see that the partitions (top and bottom of
Fig. 7.9) are different. Most countries in cluster 2 in the filled-in dataset
correspond to cluster 0in the dropped missing values dataset. Analogously, most
of cluster 0 in the filled-in dataset correspond to cluster 1 in the dropped missing
values dataset; and most countries from cluster 1 in the filled-in dataset
correspond to cluster 2 in the dropped
134 7 Unsupervised Learning
Fig. 7.10 Mean expenditure of the different clusters according to the 8 indicators of the indicators-
dropped dataset
set. Still, there are some countries that do not follow this rule. That is, looking at
both clusterings, they may yield similar (up to label permutation) results, but
theywill not necessarily always coincide. This is mainly due to two aspects: the
randominitialization of the K-means clustering and the fact that each method
works in adifferent space (i.e., dropped data in 8D space vs filled-in data,
working in 12Dspace). Note that we should not consider the assigned absolute
cluster value, sinceit is irrelevant. The mean expenditure of the different clusters is
shown by differentcolors according to the 8 indicators of the indicators-dropped
dataset (see Fig. 7.10).So, without loss of generality, we continue analyzing the set
obtained by dropping missing values. Let us now check the clusters and check their
profile by looking atthe centroids. Visualizing the eight values of the three clusters
(see Fig. 7.10), we cansee that cluster 1 spends more on education for the 8
educational indicators, while
cluster 0 is the one with least resources invested in education.
Let us consider a specific country, e.g., Spain and its expenditure on education.
If we refine cluster 0 further and check how close members are from this
cluster to cluster 1, it may give us a hint as to a possible ordering. When
visualizing the distance to cluster 0 and 1, we can observe that Spain, while being
from cluster 0, hasa smaller distance to cluster 1 (see Fig. 7.11). This should make us
realize that using 3 clusters probably does not sufficiently represent the groups of
countries. So we redothe p= rocess, but applying k 4: we obtain 4 clusters. This
time cluster 0 includes the EU members with medium expenditure (Fig. 7.12). This
reinforce the intuition about Spain being a limit case in the former clustering. The
clusters obtained are asfollows:
Fig. 7.11 Distance of countries in cluster 0 to centroids of cluster 0 (in red) and cluster 1 (in blue)
Fig. 7.12 K-means applied to the Eurostat dataset grouping the countries into four clusters
We can repeat the process using the alternative clustering techniques and
compare their results. Let us first apply spectral clustering. The corresponding
code will be as follows:
136 7 Unsupervised Learning
Fig. 7.13 Spectral clustering applied to the European countries according to their expenditure on
education
The result of this spectral clustering is shown in Fig. 7.13. Note that in general,
the aim of spectral clustering is to obtain more balanced clusters. In this way, the
predicted cluster 1 merges clusters 2 and 3 of the K-means clustering, cluster 2
corresponds to cluster 1 of the K-means clustering, cluster 0 mainly shifts to
cluster2, and cluster 3 corresponds to cluster 0 of the K-means.
Applying agglomerative clustering, not only we do obtain different clusters,
but also we can see how different clusters are obtained. Thus, in some way it is
giving us information on which the most similar pairs of countries and clusters
are. The corresponding code that applies the agglomerative clustering will be as
follows:
Case Study
137
Figure 7.14 shows the construction of the clusters using complete linkage agglom-
erative clustering. Different cuts at different levels of the dendrogram allow us to
obtain different numbers of clusters.
To summarize, we can compare the results of the three clustering approaches. We
cannot expect the results to coincide, since the different approaches are based
on different criteria for constructing clusters. Nonetheless, we can still observe
that in this case, K-means and the agglomerative approaches gave the same
results (up to apermutation of the number of cluster, which is irrelevant); while
spectral clustering gave more evenly distributed clusters. This later approach
fused clusters 0 and 2 ofthe agglomerative clustering in cluster 1, and split cluster
3 of the agglomerative clustering into its clusters 0 and 3. Note that these results
could change when usingdifferent distances among data.
138 7 Unsupervised Learning
Fig. 7.14 Agglomerative clustering applied to cluster European countries according to their expen-
diture on education
UNIT-5
Network Analysis, Graphs, Social Networks, centrality, drawing centrality of
Graphs, PageRank, Ego-Networks, community Detection
Network Analysis
Introduction
Graph is the mathematical term used to refer to a network. Thus, the field that
studies networks is called graph theory and it provides the tools necessary to analyze
networks. Leonhard Euler defined the first graph in 1735, as an abstraction of one
ofthe problems posed by mathematicians of the time regarding Konigsberg, a city
withtwo islands created by the River Pregel, which was crossed by seven bridges.
The problem was: is it possible to walk through the town of Konigsberg crossing
each bridge once and only once? Euler represented the land areas as nodes and the
bridges connecting them as edges of a graph and proved that the walk was not
possible forthis particular graph.
A graph is defined as a set of nodes, which are an abstraction of any entities
(parts of a city, persons, etc.), and the connecting links between pairs of nodes called
edges or relationships. The edge between two nodes can be directed or undirected.A
directed edge means that the edge points from one node to the other and not the
otherway round. An example of a directed relationship is “a person knows another
person”. An edge has a direction when person A knows person B, and not the reverse
direction
Basic
Definitions in Graphs 143
if B does not know A (which is usual for many fans and celebrities). An undirected
edge means that there is a symmetric relationship. An example is “a person
shook hands with another person”; in this case, the relationship, unavoidably,
involves both persons and there is no directionality. Depending on whether the edges
of a graph are directed or undirected, the graph is called a directed graph or an
undirected graph,respectively.
The degree of a node is the number of edges that connect to it. Figure 8.1
showsan example of an undirected graph with 5 nodes and 5 edges. The degree
of node Cis 1, while the degree of nodes A, D and E is 2 and for node B it is 3. If a
network isdirected, then nodes have two different degrees, the in-degree, which
is the number of incoming edges, and the out-degree, which is the number of
outgoing edges.
In some cases, there is information we would like to add to graphs to model
properties of the entities that the nodes represent or their relationships. We could
add strengths or weights to the links between the nodes, to represent some real-
world measure. For instance, the length of the highways connecting the cities in a
network.In this case, the graph is called a weighted graph.
Some other elementary concepts that are useful in graph analysis are those
weexplain in what follows. We define a path in a network to be a sequence of
nodesconnected by edges. Moreover, many applications of graphs require
shortest pathsto be computed. The shortest path problem is the problem of
finding a path betweentwo nodes in a graph such that the length of the path or
the sum of the weights ofedges in the path is minimized. In the example in Fig. 8.1,
the paths (C, A, B, E) and(C, A, B, D, E) are those between nodes C and E. This
graph is unweighted, so theshortest path between C and E is the one that follows
the fewer edges: (C, A, B, E).A graph is said to be connected if for every pair of
nodes, there is a path between them. A graph is fully connected or complete if
each pair of nodes is connected byan edge. A connected component or simply a
component of a graph is a subset of itsnodes such that every node in the subset has
a path to every other one. In the exampleof Fig. 8.1, the graph has one connected
component. A subgraph is a subset of thenodes of a graph and all the edges
linking those nodes. Any group of nodes can form
a subgraph.
Social Network Analysis
Social network analysis processes social data structured in graphs. It involves the
extraction of several characteristics and graphics to describe the main properties
of the network. Some general properties of networks, such as the shape of the
network degree distribution (defined bellow) or the average path length,
determine the type of network, such as a small-world network or a scale-free
network. A small-world network is a type of graph in which most nodes are not
neighbors of one another, butmost nodes can be reached from every other node
in a small number of steps. This is the so-called small-world phenomenon which
can be interpreted by the fact that strangers are linked by a short chain of
acquaintances. In a small-world network, people usually form communities or
small groups where everyone knows every- one else. Such communities can be
seen as complete graphs. In addition, most the community members have a few
relationships with people outside that community. However, some people are
connected to a large number of communities. These maybe celebrities and such
people are considered as the hubs that are responsible for the small-world
phenomenon. Many small-world networks are also scale-free n=et- works. In a
scale-free network the node degree distribution follows a power law (a
relationship function between two quantities x and y defined as y xn, where n
isa constant). The name scale-free comes from the fact that power laws have the
same functional form at all scales, i.e., their shape does not change on
multiplication by a scale factor. Thus, by definition, a scale-free network has many
nodes with a very few connections and a small number of nodes with many
connections. This structure is typical of the World Wide Web and other social
networks. In the following sections, we illustrate this and other graph properties
that are useful in social network analysis.
In [1]:
Basics in NetworkX
NetworkX1 is a Python toolbox for the creation, manipulation and study of the
struc- ture, dynamics and functions of complex networks. After importing the
toolbox, wecan create an undirected graph with 5 nodes by adding the edges, as
is done in the following code. The output is the graph in Fig.8.1.
import networkx as nx
G = nx . Graph ()
G. add_edge ( ’A ’, ’B ’);
G. add_edge ( ’A ’, ’C ’);
G. add_edge ( ’B ’, ’D ’);
G. add_edge ( ’B ’, ’E ’);
G. add_edge ( ’D ’, ’E ’);
nx . draw_networkx ( G)
For our practical case we consider data from the Facebook network. In particular, we
use the data Social circles: Facebook2 from the Stanford Large Network Dataset3
(SNAP) collection. The SNAP collection has links to a great variety of networks
such as Facebook-style social networks, citation networks, Twitter networks or
open communities like Live Journal. The Facebook dataset consists of a network
repre- senting friendship between Facebook users. The Facebook data was
anonymized by replacing the internal Facebook identifiers for each user with a
new value.
The network corresponds to an undirected and unweighted graph that
contains users of Facebook (nodes) and their friendship relations (edges). The
Facebook dataset is defined by an edge list in a plain text file with one edge per
line.
Let us load the Facebook network and start extracting the basic information
In[2]:
from the graph, including the numbers of nodes and edges, and the average
degree:
fb = nx . read_edgelist (" files / ch08 / faceb oo k_ com bi n ed . txt ")
fb_n , fb_k = fb . order () , fb . size ()
fb_avg_deg = fb_k / fb_n
print ’ Nodes : ’, fb_n
print ’ Edges : ’, fb_k
print ’ Average degree : ’, fb_avg_deg
The graph in Fig. 8.2 is a power-law distribution. Thus, we can say that the Face-
book network is a scale-free network.
Next, let us find out if the Facebook dataset contains more than one
connectedcomponent (previously defined in Sect. 8.2):
As it can be seen, there is only one connected component in the Facebook network.
Thus, the Facebook network is a connected graph (see definition in Sect. 8.2). We can
try to divide the graph into different connected components, which can be
potentialcommunities (see Sect. 8.6). To do that, we can remove one node from
the graph (this operation also involves removing the edges linking the node) and
see if the number of connected components of the graph changes. In the
following code, we prune the graph by removing node ‘0’ (arbitrarily selected) and
compute the number of connected components of the pruned version of the
graph:
In[5]:
fb_prun = nx. read_edgelist (
Centrality
The centrality of a node measures its relative importance within the graph. In this
section we focus on undirected graphs. Centrality concepts were first developed
in social network analysis. The first studies indicated that central nodes are
probably more influential, have greater access to information, and can
communicate their opinions to others more efficiently [1]. Thus, the applications
of centrality concepts in a social network include identifying the most influential
people, the most informed people, or the most communicative people. In practice,
what centrality means will depend on the application and the meaning of the
entities represented as nodes in the data and the connections between those
nodes. Various measures of the centrality of a node have been proposed. We
present four of the best-known measures: degree centrality, betweenness
centrality, closeness centrality, and eigenvector centrality.
Degree centrality is defined as the number of edges of the node. So the more
ties a node has, the more central the node is. To achieve a normalized degree
centrality of a node, the measure is divided by the total number of graph nodes (n)
without counting t h i−s particular one (n 1). The normalized measure provides
proportions and allowsus to compare it among graphs. Degree centrality is related
to the capacity of a node to capture any information that is floating through the
network. In social networks,connections are associated with positive aspects such
as knowledge or friendship.
Betweenness centrality quantifies the number of times a node is crossed along
the shortest path/s between any other pair of nodes. For the normalized
measure this number is divided by the total number of shortest paths for every
pair of nodes.Intuitively, if we think of a public bus transportation network, the
bus stop (node) with the highest betweenness has the most traffic. In social
networks, a person with high betweenness has more power in the sense that
more people depend on him/her to make connections with other people or to
access information from other people. Comparing this measure with degree
centrality, we can say that degree centrality depends only on the node’s
neighbors; thus, it is more local than the betweenness centrality, which depends
on the connection properties of every pair of nodes in thegraph, except pairs with
the node in question itself. The equivalent measure exists for edges. The
betweenness centrality of an edge is the proportion of the shortest paths
between all node pairs which pass through it.
Closeness centrality tries to quantify the position a node occupies in the
networkbased on a distance calculation. The distance metric used between a pair
of nodes is defined by the length of its shortest path. The closeness of a node is
inversely proportional to the length of the average shortest path between that
node and all the
other nodes in the graph. In this case, we interpret a central node as being close
to,and able to communicate quickly with, the other nodes in a social network.
Eigenvector centrality defines a relative score for a node based on its
connections and considering that connections from high centrality nodes
contribute more to the score of the node than connections from low centrality
nodes. It is a measure of the influence of a node in a network, in the following
sense: it measures the extent to which a node is connected to influential nodes.
Accordingly, an important node is connected to important neighbors.
Let us illustrate the centrality measures with an example. In Fig. 8.3, we
showan undirected star graph w=i t h n 8 nodes. Node C is obviously important,
sinceit can exchange information with more nodes than the others. The degree
centrality measures this idea. In this star network, node C has a degree
centrality of 7 or 1 if we consider the normalized measure, whereas all other
nodes have a degree of 1or 1/7 if we consider the normalized measure. Another
reason why node C is moreimportant than the others in this star network is that it
lies between each of the otherpairs of nodes, and no other node lies between C
and any other node. If node C wants to contact F, C can do it directly; whereas if
node F wants to contact B, it must go through C. This gives node C the capacity to
broke/prevent contact amongother nodes and to isolate nodes from information.
The b e t we e n n ess centrality is underneath this idea. In this example, the
— −
betweenness centrality of the node C is 28, computed as (n 1)(n 2)/2, while the
rest of nodes have a betweenness of 0. Thefinal reason why we can say node C is
superior in the star network is because C is closer to more nodes than any other
node is. In the example, node C is at a distanceof 1 from all other 7 nodes and each
other node is at a distance 2 from all other nodes, except C. So, n o−d e C has
closeness centrality of 1/7, while the rest of nodes have acloseness of 1/13. The
normalized measures, computed by dividing by n 1, are 1 for C and 7/13 for the
other nodes.
An important concept in social network analysis is that of a hub node, which is
defined as a node with high degree centrality and betweenness centrality. When
a hub governs a very centralized network, the network can be easily fragmented
by removing that hub.
Coming back to the Facebook example, let us compute the degree centrality of
Facebook graph nodes. In the code below we show the user identifier of the 10
mostcentral nodes together with their normalized degree centrality measure. We
also show the degree histogram to extract some more information from the
shape of the distribution. It might be useful to represent distributions using
logarithmic scale. We
Fig. 8.4 Degree centrality histogram shown using a linear scale (left) and a log scale for both the
x- and y-axis (right)
150 8 Network Analysis
pose the question: What happen if we only consider the graph nodes with more
than the average degree of the network (21)? We can trim the graph using degree
centrality values. To do this, in the next code, we define a function to trim the
graph based onthe degree centrality of the graph nodes. We set the threshold to
21 connections:
In[9]: def t r i m _ d eg r e e _ ce n t r a l it y ( graph , degree = 0. 01) :
g = graph . copy ()
d = nx . degree_centrality ( g)
for n in g. nodes () :
if d[ n] <= degree :
g. remove_node ( n)
return g
thr = 21. 0/( fb . order () - 1. 0)
The new graph is much smaller; we have removed almost half of the nodes
(we have moved from 4,039 to 2,226 nodes).
The current flow betweenness centrality measure needs connected graphs, as
does any betweenness centrality measure, so we should first extract a connected
compo- nent from the trimmed Facebook network and then compute the
measure:
In [10]: fb_subgraph = list ( nx . connect e d _ c o m p o n e n t_ s u b g r ap h s (
fb_trimed ))
print ’# subgraphs found : ’, size ( fb_subgraph )
print ’# nodes in the first subgraph : ’,
len ( fb_subgraph [0])
betweenness = nx. b e t w e en ne s s _ c e n t ra l i t y ( fb_subgraph [0])
print ’ Trimmed FB betweenness : ’,
sorted ( betweenness . items () , key = lambda x: x [1] ,
reverse = True ) [: 10]
current_flow = nx . c u r r e nt_ f l o w _ b e tw e e n n es s _ c e n tr a li t y (
fb_subgraph [0])
print ’ Trimmed FB current flow betweenness : ’,
sorted ( current_flow . items () , key = lambda x: x [1] ,
reverse = True ) [: 10]
152 8 Network Analysis
In this section we focus on graph visualization, which can help in the network
dataunderstanding and usability.
The visualization of a network with a large amount of nodes is a complex task.
Different layouts can be used to try to build a proper visualization. For instance,
we can draw the Facebook graph using the random layout (nx.random_layout),
but this is a bad option, as can be seen in Fig. 8.5. Other alternatives can be more
useful. In the box below, we use the Spring layout, as it is used in the default function
(nx.draw), but with more iterations. The function nx.spring_layout returns the
position of the nodes using the Fruchterman–Reingold force-directed algorithm.
8.4 Centrality 153
This algorithm distributes the graph nodes in such a way that all the edges are
more or less equally long and they cross themselves as few times as possible.
Moreover, we can change the size of the nodes to that defined by their degree
centrality. As can be seen in the code, the degree centrality is normalized to
values between 0 and 1, and multiplied by a constant to make the sizes
appropriate for the format of the figure:
In [11]: pos_fb = nx . spring_layout ( fb , iterations = 1000)
The resulting graph visualization is shown in Fig. 8.6. This illustration allows us
to understand the network better. Now we can distinguish several groups of nodes
or “communities” clearly in the graph. Moreover, the larger nodes are the more
centralnodes, which are highly connected of the Facebook graph.
We can also use the betweenness centrality to define the size of the nodes. In this
way, we obtain a new illustration stressing the nodes with higher betweenness, which
are those with a large influence on the transfer of information through the
network. The new graph is shown in Fig. 8.7. As expected, the central nodes are
now those connecting the different communities.
Generally different centrality metrics will be positively correlated, but when
theyare not, there is probably something interesting about the network nodes. For
instance, if you can spot nodes with high betweenness but relatively low degree,
these are thenodes with few links but which are crucial for network flow. We can
also look for
154 8 Network Analysis
the opposite effect: nodes with high degree but relatively low betweenness.
These nodes are those with redundant communication.
Changing the centrality measure to closeness and eigenvector, we obtain the
graphs in Figs. 8.8 and 8.9, respectively. As can be seen, the central nodes
arealso different for these measures. With this or other visualizations you will be
able to discern different types of nodes. You can probably see nodes with high
closeness centrality but low degree; these are essential nodes linked to a few
important or active nodes. If the opposite occurs, if there are nodes with high
degree centrality but lowcloseness, these can be interpreted as nodes embedded
in a community that is far removed from the rest of the network.
In other examples of social networks, you could find nodes with high closeness
centrality but low betweenness; these are nodes near many people, but since
there may be multiple paths in the network, they are not the only ones to be
near many people. Finally, it is usually difficult to find nodes with high
betweenness but low closeness, since this would mean that the node in question
monopolized the links from a small number of people to many others.
PageRank
rank computation as a random walk through the network. We start with an initial equal
probability for each page: v0 = ( 1 ,n. . . , 1 ),nwhere n is the number of nodes. Then
we can compute the probability that each page is visited after one step by applying
the transition matrix: v1 = Mv. The probability that each page will be visited after
k steps is given by vk =Mka. After several steps, the sequence converges to a
unique probabilistic vector a∗ which is the PageRank vector. The i -th element of
this vector is the probability that at each moment the surfer visits page Pi . We need a
nonambiguous definition of the rank of a page for any directed web graph.
However,
in the Internet, we can expect to find pages that do not contain outgoing links
and this configuration can lead to certain problems to the explained procedure.
In order to overcome this problem, the algorithm fixes a positive constant p
between 0 and 1 (a typical value for p is 0.85) and redefines the transition
matrix of the graph by
R = (1 − p) M + p B, where B = 1 I , annd I is the identity matrix. Therefore, a
node with no outgoing edges has probability n of moving to any other node.
Let us compute the PageRank vector of the Facebook network and use it to define
the size of the nodes, as was done in box In [11].
In [12]: pr = nx . pagerank ( fb , alpha = 0. 85)
nsize = np . array ([ v for v in pr . values () ])
nsize = 500*( nsize - min ( nsize )) /( max ( nsize ) - min ( nsize ))
nodes = nx . draw_n etw or kx _ nod es ( fb ,
pos = pos_fb ,
node_size = nsize )
edges = nx . draw_networkx_edges ( fb ,
pos = pos_fb ,
alpha = . 1 )
The code above outputs the graph in Fig. 8.10, that emphasizes some of the
nodeswith high PageRank. Looking the graph carefully one can realize that there
is one large node per community.
8.5 Ego-Networks
nodetype = int )
p r i nt ’ Nodes of the ego g r ap h 1 0 7: ’, l en ( G_107 )
G = nx . read_edgelist (
os . path . join ( ’ files / ch08 / facebook ’,
’{0}. edges ’. format ( ego_max )) ,
nodetype = int )
print ’ Nodes : ’, G. order ()
print ’ Edges : ’, G. size ()
print ’ Average degree : ’, G_k / G_n
The most densely connected ego-network is that of node ‘1912’, which has an
average degree of 40. We can also compute which is the largest (in number of nodes)
ego-network, changing the measure of sizes from G.size() by G.order(). In this case,
we obtain that the largest ego-network is that of node ‘107’, which has 1,034
nodes and an average degree of 25.
Next let us work out how much intersection exists between the ego-networks
inthe Facebook network. To do this, in the code below, we add a field ‘egonet’ for
every node and store an array with the ego-networks the node belongs to. Then,
having thelength of these arrays, we compute the number of nodes that belong to
1, 2, 3, 4 andmore than 4 ego-networks:
In [16]: # Add a field ’ egonet ’ to the nodes of the whole facebook
network .
# Default value egonet = [] , meaning that this node does not
belong to any ego - netowrk
for i in fb . nodes () :
fb . node [ str (i) ][ ’ egonet ’] = []
# Fill the ’egocolor’ field with a different color numberfor each ego-network in
ego_ids:
id Color = 1
for id in ego_ids :
G = nx.r ead_edgelist(
os.path.join(’files/c h08/facebook’,
’{0}.edges’.format(id)),nodetype = int)
for n in G.n odes () :
fb.n ode[str(n)][’egocolor’] = id Colorid Color += 1
However, the graph in Fig. 8.12 does not illustrate how much overlap is there
between the ego-networks. To do that, we can visualize the intersection between
ego-networks using a Venn or an Euler diagram. Both diagrams are useful in order to
see how networks are related. Figure 8.13 shows the Venn diagram of the
Facebook network. This powerful and complex graph cannot be easily built in
Python tool-
162 8 Network Analysis
boxes like NetworkX or Matplotlib. In order to create it, we have used a JavaScript
visualization library called D3.JS.4
Community Detection
fb , pos = pos_fb ,
cmap = plt . get_cmap (’ Paired ’),
node_color = colors2 ,
node_size = nsize ,
with_labels = False )
edges = nx . d r a w _ n e t wo r k x _e d g e s ( fb , pos = pos_fb , alpha = .1)
.
Community Detection 163