Notes Machine Learning
Notes Machine Learning
DECAP737
Edited by
Dr. V Devenderan
Machine Learning
Edited By:
Dr. V Devenderan
Content
Objectives
Understanding the concepts of machine learning.
Understanding the difference between variousmachine learning approaches.
Understanding various basic data types.
Understanding the major tasks in preprocessing.
Understanding the real time applications of machine learning.
Introduction
A computer program is said to learn from experience with respect to some class of tasks and
performance measure, if the performance at the tasks, as measured by performance measure,
improves with the experience. In this unit, the concepts of machine learning are discussed in detail.
The different types of machine learning approaches are discussed using examples. The preparation
of the data sets is discussed along with basic data types and data cleaning operations. There is a
important part in machine learning, known as preprocessing and feature engineering are also
highlighted.
Machine Learning
observations unseen by the machine during training. Huge data collection and storage technologies
have altered the landscape of scientific data analysis, which includes natural resources, prediction
of floods, astronomy, biology and etc. Machine learning is present in all those examples.
The above representation as given in Table 1, depicts the input as N instances, s(1), s(2), … S(N),
each is an example of the concept to be learned. Each instances provides the input to the machine
learning algorithm, and is categorized by its values mentioned as y, as in the last column. The data
can be understood in more elaborated, as given below.
Four types of data are explained here, as it is often be handled in the process of dataset preparation
or preprocessing. The data types are as given below.
Numerical Data
Categorical Data
Time Series Data
Text Data
Numerical Data
Numerical data is a datatype expressed in numbers. This further classified as continuous and
discontinuous data as in Figure 2.
Categorical Data
Categorical data is a collection of information that is divided into groups. They are further divided
into two types such as ordinal and nominal.
Ordinal Data
Ordinal data has ranking / ordering. Ordinal features are sorted or ordered as in the figure 3.
Size of T-Shirt - S, M, L, XL.
Convert string values into integer as per order like XL > L > M > S.
Nominal Data
Nominal features are not ordered as in figure 4. Nominal data has No ranking / order.
Colourof T-Shirt: Red, Green, Blue.
Assign numeric value to each feature.
0 -> Red, 1 -> Green, 2 -> Blue
Machine Learning
Text Data
Text data usually consists of documents, which can represent words, sentences or even paragraphs.
Usually, digital information can be categorized into two classes. They are structured and
unstructured. Studies have recently revealed that more than 70 percent of all the data available for
corporations today is unstructured. But, structured data fits into a fixed format or data table, what
we discussed in Table 1 above.
Preprocessing is the process of fixing or removing incorrect, corrupted, incorrectly formatted,
duplicated, or incomplete data within a dataset. Depicted in Figure 6. This is mainly focusing on
dealing with missing data and handling categorical data.
Machine Learning
Machine Learning
person is saying. Spell checking, grammar checking, translation are the other applications of
NLP and etc.,
Fault diagnostic: Preventive upkeep of motors and generators and other electro-mechanical
devices, can delay malfunctions. Otherwise the deviceswill interrupt industrial
[Link], typical defects or flaws include misalignment of shaft, mechanical
slackening, defective bearings, and unbalanced pumps. Diagnostic of faults are performed
using machine learning algorithms, which is extremely helpful in this field.
Business intelligence: Business intelligence technologies offer not only historical and current
information but also predictive views of business applications. It is essential for businesses to
be able to comprehend the commercial control of their organization, in term of customer base,
market, supply and resources, and competition. In the absence of data mining, many
businesses may be unable to effectively perform market analysis, compare customer feedback
on similar products, find the strength and weaknesses of their competitors, retain extremely
valuable customers, and arrive at intelligent business decisions.
Summary
In this unit, the concepts of machine learningare discussed along with the different approaches of
machine learning. Each approach is discussed in detail with examples. The differences in each of
the approaches would be better understood. Data set is very important for machine learning.
Hence, it is necessary to understand about the basic data types, which is also explored thoroughly.
This will help to convert or process the obtained data. But, there was also lot of challenges in
processing the data set. This also covered in the name of preprocessing and data cleaning. The
major tasks of preprocessing and the possible ways of data cleaning were also discussed. The
terminology – feature engineering was highlighted as it was related to data cleaning.
Keywords
Dataset
Preprocessing
Datacleaning
Supervised learning
Unsupervised learning
Reinforcement learning
Self Assessment
1. Machine learning approach, which build a model based on sample data, is known as
_______.
A. Supervised
B. Unsupervised
C. Reinforcement
D. None of the above
6. Justify the statement. “Preprocessing is the process of converting raw data into data which
will be suitable for machine learning”.
A. True
B. False
10. _________ is the process of changing the format, structure or values of data.
A. Data integration
B. Data cleaning
Machine Learning
C. Data transformation
D. Data Preprocessing
6. A 7. D 8. A 9. C 10. C
Review Questions
1. Explain the different types of data.
2. Differentiatenominal and ordinal data types.
3. Give examples for categorical data.
4. List out the methods used for filling the missing values.
5. Identify the machine learning algorithms for each machine learning approaches.
Further Readings
MadanGopal, Applied Machine Learning, McGraw Hill Education, India, 2018.
S. N. Sivanandam, S.N. Deepa, Principles Of Soft Computing, Wiley Publications,
Second Edition, 2011.
Rajasekaran, S., Pai, G. A. Vijayalakshmi, Neural Networks, Fuzzy Logic and Genetic
Algorithm Synthesis And Applications, Prentice Hall of India, 2013.
N. P. Padhy, S. P. Simon, Soft Computing With Matlab Programming, Oxford
University Press, 2015.
Web Links
[Link]
[Link]
[Link]
3a5e293a5114
Objectives
1. To understand the online tools used for python such as JupyterLab and Google Colab.
2. To understandthe fundamentals of programming such as Variables, keywords, Data types,
Expression, Statements, Operator and Operator Precedence.
3. To differentiatethe conditional and unconditional statements from simple if, if-else, nested if, for
loop, while loop, break and continue.
4. To understand the use of function and recursion which will bediscussed with examples.
5. To know the packages in python along with their purposes.
Introduction
In this unit, we try to introduce you the very popular programming language called Python. We
know that there are many programming languages such as C, C++, which were already existed and
used for decades. Here, we will try to understand the merits of python language over others.
Moreover, we will be writing a simple python programand try to execute using an online tool.
Programs can be experimented to understandthe conditional, unconditional statements along with
functions and recursion. Function declaration, calling of functions, parameters can be well
understood from the given examples. Let us begin with what is python.
current version of python is 3.9.7. There are many reasons for its popularity. It is readable like an
English statement having simple syntaxes. Python is a general-purpose open source language.
Python is portable language, so that it runs on many Unix variants including Linux and mac OS,
and on Windows. Python is also an interpreted language, interactive language and object-oriented
programming language. Python codes are executed comparatively little faster.
The language offers multiple ready made libraries such as NumPy, SciPy, MatplotLib, Scikit-Learn
and frameworks which will support the initial phase of development. These are all the reasons
made Python very popular among programming community.
Online Tools
Jupyter Notebook and Google Colab are the popular online tools for programming in python. Let
us first discuss the Jupyter. You will get the access in this link: [Link] Once you
have visited the page, it will look like the figure 2 given below.
Now please select the first blue color button “Try Classic Notebook”. The page will be looking like
like the figure 3 given below.
Python Installation
Python softwares and the installation manual can be downloaded from the link
[Link] You will be shown the opt version with respect to your
system configuration and operating system. Latest version will be Python 3.9.7 as shown in the
figure.
Just a click is enough to download. And the procedures are simple for the installation.
Variables
Variable is a name that refers to a value that may be changed in the [Link] is no command
to declare a variable in python.
Datatype
Variables can store different types of data. They are Numeric Data Types, Boolean Data Type, Set
Data Type, Dictionary and Sequence Data Types as shown in the figure. Let us start with Numeric
Data Types, where only the numbers are involved, whichis again divided into three categories such
as integer (without decimals), float (with decimals)and complex [Link] data will be
storing True or False [Link] will be studied in the coming units in detail.
Keywords
There are some predefined and reserved words have special meaning to python. Those words are
called Keywords. These keywords can not be used as name for the variable / identifier, not to be
used as function names. These are otherwise called as system defined variable. There are more 30
keywords used in python. Few keywords are like, and, or, not, if, elif, else, for, while, break, return,
True, False, continue, in, is, import and etc.
Expression
An expression is a combination of values, variables and operators. This can be understood from an
example given in the following figure. There are three variables a, b and c. The variables are known
as operands. Operators are used in between to perform some operations using the operands. In this
case, plus (+) operator, multiplication (*) operators are used. Final result is stored in the variable
result.
Let us have an example for an expression. Let a = 10, b=5, c = 3. What will be the output of the
above expression?The output is 25 as shown in the figure.
Statements
Statements are the instructions given in the source code for [Link] outcome of the program
is depending upon how all the statements are arranged for execution. The statements are executed
in a sequential order starting from the first statement in program. There are three types of
statements in python. They are Assignment statements, Conditional Statements and Looping
Statements, which are discussed below.
Assignment statements
The statements that are used to copy a value into the variable is called assignment statements. The
equal sign (=) is used for copying the value. Hence, the operator (=) is called assignment operator.
The target of an assignment statement is written on the left side of the equal sign (=). The value
what is to be assigned will be in the right side of the equal sign (=).
For example, a = 100 is the assignment statement. Here the value 100 is assigned to the variable a.
And, we have one more example like this. x, y = 50, 100 is also the assignment statement, where the
value 50 is assigned to variable x and the value 100 is assigned to variable y.
Conditional statements
Any statementthat outputs the Boolean value (True / False) is called conditional statement as given
in the figure. Framing of conditions is the key element in controlling the flow of execution. Let us
have an example of conditional statement.
Example 1 : ( a < b )
Looping statements
The looping statement(s) are a statementor a block of statements that are used to execute repeatedly
until a specified condition is satisfied. When the condition is True, it executes and when the
condition is False, it stops the [Link] the execution is not getting stopped, then the looping
statement will become infinite [Link] are different looping statements are available such as
while loop and for loop.
Operator
The operators are used to perform some mathematical operations on the values and the variables.
There are few standard symbols available in python. Let us have a look on list of operators and
their usages. According to their usages, all the operators are grouped in different categories such as
arithmetic operators, Relational Operators and logical operators.
Arithmetic Operators
+ Addition x+y
- Subtraction x-y
// Division (floor) x // y
% Modulus x%y
** Power x ** y
Relational Operators
These operators are used to compare the values or variables. The output of relational operators will
be either True or False.
== Equal to x=y
!= Not equal to x != y
Logical operators
Logical operators are used to combine two or more conditional statements. The operators are
Logical AND, Logical OR and Logical NOT.
or Logical OR x or y
Assignment operators
These are used to assign the values to the variable. This operator was already discussed in the topic
of Assignment Statements. Here, let us have the list of other operators used for assignments
operation.
+= This is simplification of a = a + b a += b
-= This is simplification of a = a - b a -= b
*= This is simplification of a = a * b a *= b
/= This is simplification of a = a / b a /= b
%= This is simplification of a = a % b a %= b
Operator Precedence
It is understood that an expression is having one or more operators and operands having simple or
complex mathematical operations. Two operands are needed for an operator to perform the
specified operation. Hence, some order of preference or priority is required to select the operators
to compute the expression. This is called as operator precedence. It can be understood from a
simple expression as shown in the figure.
In the above figure, the expression first computes the multiplication operator and then the result of
the multiplication is used for the next computation of addition operator. Here, multiplication
operator is having the higher priority than the addition operator. Similarly, there are many other
operators are available as we know. It is important to know their precedence so that we can use
them correctly as per our requirements in the expression. Following figure is trying to give you the
clear picture of precedence; the higher priority starts from top and reaching the lowest priority in
the bottom.
2.3 IF Statement
The flow of execution in a program can be controlled using the proper conditions. Here, is the
simple conditional statement called if statement. This is used to execute a block of statements if the
condition is True and to execute the next statements if the condition is False. Hence, the flow of
execution lies in the decision making as in the figure.
attendance = 90
if (attendance>= 75):
print (“Eligible for final examination”)
Here the variable attendance is having 90. Hence, condition is satisfied and the print statement is
executed successfully. Let us have the same example with the attendance value as 65.
attendance = 65
if (attendance>= 75):
print (“Eligible for final examination”)
What will be the output? Of course, it doesn’t print anything as there are no statements given when
the condition becomes False. This can be solved in the next type of conditional statement.
If the condition (if expression) is False, the control is going to false block and reaches the end.
Similarly, if the condition is false, the control is going to true block and reaches the end. Let us
discuss this using an example.
x=6
y=8
if (x>y):
print (“x is greater than y”)
else:
print (“y is greater than x”)
Here, let the variables x and y has the values 6 and 8 respectively. Now, concentrate onthe if
statement and find out the value of condition. (x > y) ( 6 > 8 ) False. The control goes to the
False Part and outputs “y is greater than x”. In case, if we change the values as x= 8 and y=6. What
will be the output?
x = 86
y = 70
if (x>y):
print (“ x is greater than y”)
else:
print (“y is greater than x”)
yes, we will get the output as “x is greater than y” as the condition becomes True and True Part has
been executed.
On every successful execution of the statement, it goes back to the condition after
increments/decrement the variable and checks the condition still satisfied or not. If satisfied, it
continues to execute the statement again and repeat the same till the condition is failed. Let us have
an example.
for t in range (5):
print (t)
The above example is having the variable t. The initial value will be 0 in this case. The last value
will be 4. Before explaining this, let us take care of what is range function.
This function will create the sequence of numbers in a given range starting from 0 by default. In
this, having range (5) will give values from 0 to [Link] is making the sequence of numbers easy.
Now, let us focus on the output of the for loop statement given above. Here, print (t) is executed
five times.
Output:
0
1
2
3
4
Let me explain you from a simple example [Link] variable used is number having initial value
as 0. Here, the program aims to execute a block of statement till the variable number is not equal to
8, It means it never knows how many times it is going to execute the block of statement. We need to
manage this condition as per our requirements. Here, the task is simple.
Initially, the value of number is 0. The condition (0 not equal to 8) is True. It executes the block of
statements first time. Now, the value of number is increased by 1 and it becomes number = 1. Now,
it checks the condition again. The condition (1 not equal to 8) is True. It executes the block of
statements second time and it goes on till the condition is True. Stops otherwise.
Break statement
This statement is used to stop the current execution. There is no need to give any condition for this
break statement. This statement is used whenever you need to stop or whenever you find any
exceptions during the execution. The usage of break statement is understood from an example
given below.
x = 100
while ( x < 600) :
print (x)
if ( x == 300) :
break
x = x + 100
There is a variable x in the example having the initial value as [Link]-loop executes till the value
of x is less than 600. On every execution, the value of x is incremented by 100. But, as there is a
break statement, planned to be executed exactly when x = 300. Hence, it stops the current execution
at that point and never continues the loop further.
Continue Statement
This statement is used to continue to the next iteration (loop) without executing further statements
in the current iteration (loop). There is no need to give any condition for these continue statement.
This statement is used whenever you need to avoid the further statements and want to execute the
next iteration. The usages of continue statement is understood from an example given below.
x = 100
while (x< 600):
print (x)
if (x == 300):
continue
x = x + 100
There is a variable x in the example having the initial value as 100. While-loop executes till the
value of x is less than 600. On every execution, the value of x is incremented by 100. But, as there is
a continue statement, planned to be executed exactly when x = 300. Hence, it stops the current
execution at that point and continues to the next iteration(loop). Means, once the continue
statement is executed, further statementsi.e., increment will not be executed and the value of x
remains as 300. So, the loop will further become infinite loop as the condition will not become False
at any case, as there is no increment of value of x.
2.8 Functions
Function is a block of statements, whichis executed only when it is called. Function is given a
specific name. We can use that name whenever we want to call that function. Function can be
divided into twotypes. They are system-defined function and user-defined function. Let us focus
more on the user-defined function. Declaration of function and calling of functions are discussed
here. The following figure represents the usage of passing a value (x) to the function (f) and getting
the output. Function is called by sending the value of x. Function is using the value of x and
performing the computation. The result is sent back as the final output.
We know that a function that you define yourself in a program is known as user defined function.
The function definition and declaration is well understood from the example given below. We are
defining a function using the keyword “def”. The name of the function is “fahr_to_celsius”. This
function accepts only one parameter i.e., temp. The computed value is returned from the function
using the keyword “return” as given in the figure. This function does the converting the
temperature into Fahrenheit.
Here is one more example, which accepts two parameters a and b. Addition of giventwo numbers
is performed in the function. The function name is my_fun. We are not returning anything from the
[Link] is noreturn statementexist in the function.
The values or variables given in the function definition are called as parameters. At the same time,
the values or variables given in the calling function is called and arguments. The number of
parameters should be matching with the number of arguments that are passed to the function. The
order of passing the values is very important in passing into the parameters.
Once it is defined, the function cannot be executed until it is called by its name. That's why the
statement, which is used to call any function, is known as calling function. From the figure given
below, we can understand that the function is called by the statement myfun(3, 4). Parameters are
passed during calling the function. It is assumed as 3 is going to variable x and 4 is going to
variable y. Multiplicated value (3 x 4 = 12) is returned as the final output.
Here, we can see an example where we are going to calculate the factorial of a given number say n.
The function name is fac ( ) . The recursive function is the one which is getting called by itself.
Hence, you are using the same function name wherever you need to call the function. The recursive
will go until you reach n = 0.
The output of the above recursion function is understood in the following manner.
Summary
The fundamentals of python programming such as Variables, keywords, Datatypes,
Expression, Statements, Operator and Operator Precedence were discussed.
Understood how to write a simple python program in the online tools such as JupyterLab and
Google Colab.
We could able to differentiate the conditional and unconditional statements. Illustrated with
examples.
The usage of simple functions and recursion functions were discussed with examples.
Few real time applications also elaborated here to understand the popularity of python.
Keywords
Python
Jupyter
Colab
Operators
Functions
Packages
Self Assessment
1. What is the output of the following code?
x = 10 // 3
print(x)
A. 0
B. 1
C. 2
D. 3
A. 0
B. 1
C. 2
D. 3
A. 325
B. 148
C. 0
D. 100
A. Finite Loop
B. Infinite Loop
A. 15
B. 0
C. 35
D. 45
A. 0, 2, 4, 6
B. 0, 1, 2, 3, 4
C. 0, 2, 4
D. 1,2,3,4,5
A. 1 time
B. 5 times
C. Infinite Loop
D. None of the above
8. How many times the print statement is executed in the given code?
x = 10
while (x <= 10):
print(x)
x=x-2
A. 5 times
B. 10 time
C. Infinite Loop
D. None of the above
9. How many times the print statement is executed in the given code?
x = 10
while (x <= 10):
print(x)
continue
x=x-5
break
A. 10 times
B. 2 times
C. Infinite Loop
D. None of the above
10. How many times the print statement is executed in the given code?
x = 10
while (x <= 10):
print(x)
break
x=x-5
continue
A. 1 time
B. 5 times
C. 10 times
D. Infinite Loop
A. All good
B. All bad
C. Both (A) and (B)
D. None of the above
A. Grade O
B. Grade A
C. Grade B
D. Grade C
13. What is the output of the following nested-if code? Ans: Grade B
x=90
if (x >= 90):
print("Grade O")
else:
if (x >= 80):
print("Grade A")
else:
if (x >= 70):
print("Grade B")
else:
if (x >= 60):
print("Grade C")
A. Grade O
B. Grade A
C. Grade B
D. Grade C
A. 0
B. 45
C. 55
D. None of the above
A. (10, 20)
B. (20, 30)
C. Nothing is printed.
D. None of the above
6. C 7. C 8. C 9. C 10. A
Review Questions
1. Explain the Datatypes and their functionalities.
2. Differentiate conditional and unconditional statements. Give the respective name of the
statements.
3. Illustrate finite and infinite loop. Give reasons for getting infinite loop.
4. How do you receive the output from the function? Explain with an example.
5. Why do you need Recursive Function? How it stops the recursive operation.
Further readings
John Zelle, “Python Programming: An Introduction to Computer Science“, Second
Edition, Franklin, Beedle and Associates Inc, 2009.
Web Links
[Link]
[Link]
[Link]
[Link]
[Link]
Objectives
To understandthe concepts of Data Preprocessing and Data Analysis.
To understandthe fundamentals of datasetand downloading from the website.
To understand the python code for preprocessing of data.
To understand the process of data wrangling with examples.
To know the different aspects of exploratory data analysis.
Introduction
Data preprocessing is a process of preparing the raw data and making it suitable for a machine-
learning model. It is the first and crucial step while creating a machine-learning model because the
real world data generally contains noises, missing values and may be in an unusable format, which
cannot be directly used for machine learning model. Hence, the data preprocessing is required
tasks for cleaning the data and making it suitable for a machine-learning model, which also
increases the accuracy and efficiency of a machine-learning [Link] this unit, we will discuss and
understand the fundamentals of data preprocessing and the necessary steps and approaches in
doing the preprocessing. Also, we explore the concept of data analysis and we try to understand
how the data wrangling and exploratory data analysis helps for effective data preprocessing.
important in the approach of data preprocessing. The process of data analysis consists of the
following steps.
Gathering the Requirement for Data: This helps you to decide the need for the data, what
type of data you want to use, and what data you plan to analyze.
Data Collection:It’s time to collect the data from your sources. Data collection will be done
from your identified requirements.
Data Cleaning: It’s time to clean up the collected data. Assume that some of your collected
data is useful and some of data is not useful. The cleaning techniques are given in Fig 1. This
process is where you remove white spaces, duplicate records, and basic errors. Data cleaning
is mandatory before sending the information for data analysis.
analysis method derives data via words, symbols, pictures, and observations. This method doesn’t
use statistics. But, the Quantitative Data Analysisproduces different numbers as the result of data
analysis with the help of statistical methods. Statistical data analysis methods collect raw data and
process it into numerical data.
Basic Information about the dataset is obtained from the following code.
print([Link] ())
Univariate Plots
Here, 'uni' means one and ‘variate’ indicates a variable. Therefore, univariate plot is a form of
diagram / graph that only involves single [Link] is given in Fig 3.
Multivariate Plots
Multivariate plots help us to understand the interactions between the variables. For example, we
look at different variables (or factors) and how they might impact certain situations or outcomes.
Consider the marketingscenario, you might look at how the variable_1i.e., “money spent on
advertising” impacts the variable_2 i.e., “number of sales”. Here, we are considering two variables
for the analysis and the same is put up in the visualization just like Fig 4.
df = [Link](data)
# Display data
df
Dealing with missing values:
# Compute average
c = avg = 0
for ele in df['Marks']:
if str(ele).isnumeric():
c += 1
avg += ele
avg /= c
# Replace missing values
df = [Link](to_replace="NaN",
value=avg)
Reshaping data:
# Categorize gender
df['Gender'] = df['Gender'].map({'M': 0,'F': 1, }).astype(float)
Filtering data:
# Filter top scoring students
df = df[df['Marks'] >= 75]
proportion (count/total count) of cases for a range of [Link] plot, which graphically depicts the
five-number summary of minimum, first quartile, median, third quartile, and maximum.
Multivariate non-graphical:
Multivariate data arises from more than one variable. Multivariate non-graphical EDA techniques
generally show the relationship between two or more variables of the data through cross-tabulation
or statistics.
Multivariate graphical:
Multivariate data uses graphics to display relationships between two or more sets of data. The most
used graphic is a grouped bar plot or bar chart with each group representing one level of one of the
variables and each bar within a group representing the levels of the other [Link] common
types of multivariate graphics include, Scatter plot, which is used to plot data points on a
horizontal and a vertical axis to show how much one variable is affected by [Link]
chart, which is a graphical representation of the relationships between factors and a [Link]
chart, which is a line graph of data plotted over [Link] chart, which is a data visualization that
displays multiple circles (bubbles) in a two-dimensional [Link] map, which is a graphical
representation of data where values are depicted by color.
Summary
The concepts of Data Analysis areintroduced.
We understood the fundamentals of dataset and downloading from the website.
The process of data wrangling is discussed with examples.
We came to know about different aspects of exploratory data analysis and their types.
We have seen the necessary python code for preprocessing, data visualization and others.
Necessary Python code is given to explain the data preprocessing and other relevant concepts.
Keywords
Data Analysis
Import and Export
Data Preprocessing
Data Wrangling
Exploratory Data Analysis
Self Assessment
1. Data Analysis is a process of?
A. Inspecting data
B. Cleaning data
C. Transforming data
D. All of the above
A. Statistical figures
B. Numerical aspects
C. Statistical methods
D. None of the mentioned above
8. What is a hypothesis?
A. A statement that the researcher wants to test through the data collected in a study
B. A research question the results will answer
C. A theory that underpins the study
D. A statistical method for calculating the extent to which the results could have happened by
chance
10. Which of the following graph can be used for simple summarization of data?
A. Scatter plot
B. Overlaying
C. Bar plot
D. All of the mentioned
12. Which of the following gave rise to need of graphs in data analysis?
A. Data visualization
B. Communicating results
C. Decision making
D. All of the mentioned
14. The plot method on Series and Data Frame is just a simple wrapper around _______.
A. [Link]()
B. [Link]()
C. [Link]()
D. None of the mentioned
15. Which of the following is not true about series and data frames?
A. Both are size mutable.
B. Both can be derived from pandas.
C. Both can be reshaped into different forms.
D. Both can be created by passing data in form of list, dictionaries and ndarray.
6. C 7. B 8. A 9. D 10. C
Review Questions
1. Explain the importance of data analysis.
2. Give the different approaches for data cleaning.
3. Give the python code for importing the data from UCI repository.
4. Differenciateunivariate and multivariate analysis with examples.
5. Whydata wrangling is used?Give the various steps involved in this.
Further Readings
John Zelle, “Python Programming: An Introduction to Computer Science“, Second
Edition, Franklin, Beedle and Associates Inc, 2009.
Applied Machine Learning by MadanGopal, McGraw Hill Education, India, 2018.
Machine Learning by Tom Mitchell, McGraw Hill Education, India, 2017.
Principles of Soft Computing by S. N. Sivanandam and S. N. Deepa, Wiley, India, 2018.
Web Links
[Link]
[Link]
[Link]
[Link]
[Link]
visualization-techniques-in-data-science/
Objectives
To implementthe concepts of Data Preprocessing and Data Analysis.
To implementthe importing and exporting of datasets.
To understand the python code for preprocessing of data.
To draw different types of graphs using matplotlib and pandas packages.
To understand the process of data wrangling with examples.
Introduction
Data preprocessing is a process of preparing the raw data and making it suitable for a machine-
learning model. It is the first and crucial step while creating a machine-learning model because the
real world data generally contains noises, missing values and may be in an unusable format, which
cannot be directly used for machine learning model. Hence, the data preprocessing is required
tasks for cleaning the data and making it suitable for a machine-learning model, which also
increases the accuracy and efficiency of a machine-learning [Link] this unit, we will discuss and
understand the fundamentals of data preprocessing and the necessary steps and approaches in
doing the preprocessing. Also, we explore the concept of data analysis and we try to understand
how the data wrangling and exploratory data analysis helps for effective data preprocessing.
Fig 7. Getting First four columns from the iris data set
The last column is the target / labels used for classification purposes. The following code will help
us if we want to know what it is. We can use it if it is necessary. Fig 8 depicts the python code.
Univariate Plots
Let us explore the first type of visualization i.e., univariate plots. Here, 'uni' means one and‘variate’
indicates a variable. Therefore, univariate plot is a form of diagram / graph that only involves
single variable as in Fig 9, 10 and 11.
Multivariate Plots
Multivariate plots help us to understand the interactions between the variables. Here, we are
considering two variables for the analysis and the same is put up in the visualization using
matplotlib package as in Fig 12.
Summary
Implemented the concepts of Data Preprocessing and Data Analysis.
Implemented the importing and exporting of datasets.
Understood the python code for preprocessing of data.
We understood how to draw different types of graphs using matplotlib and pandas
packages.
Understood the process of data wrangling with examples.
Keywords
Import and Export
Data Preprocessing
Pandas
Matplotlib
Data Wrangling
Self Assessment
Q1) Data Analysis is a process of?
A. Inspecting data
B. Cleaning data
C. Transforming data
D. All of the above
Q2) How many main statistical methodologies are used in data analysis?
A. 2
B. 3
C. 4
D. 5
Q6) Which of the following is the correct extension of the Python file?
A .python
B .pl
C .py
D .p
A Function
B def
C Fun
D Define
Q10) Which of the following graph can be used for simple summarization of data?
A Scatter plot
B Overlaying
C Bar plot
D All of the mentioned
A True
B False
Q12) Which of the following gave rise to need of graphs in data analysis?
A Data visualization
B Communicating results
C Decision making
D All of the mentioned
Q14)The plot method on Series and DataFrame is just a simple wrapper around _______.
A [Link]()
B [Link]()
C [Link]()
D None of the mentioned
6. C 7. B 8. A 9. D 10. C
Review Questions
1. Explain the importance of data analysis.
2. Give the different approaches for data cleaning.
3. Give the python code for importing the data from UCI repository.
4. Differentiateunivariate and multivariate analysis with examples.
5. Whyis data wrangling used?Give the various steps involved in this.
6. How to remove the duplicate entries from the dataset?
7. Illustrate the fundamentals of exploratory data analysis.
8. Give the types of exploratory data analysis.
Further Readings
John Zelle, “Python Programming: An Introduction to Computer Science“, Second
Edition, Franklin, Beedle and Associates Inc, 2009.
Applied Machine Learning by MadanGopal, McGraw Hill Education, India, 2018.
Machine Learning by Tom Mitchell, McGraw Hill Education, India, 2017.
Principles of Soft Computing by S. N. Sivanandam and S. N. Deepa, Wiley, India, 2018.
Web Links
[Link]
[Link]
[Link]
[Link]
m
[Link]
visualization-techniques-in-data-science/
Objectives
learn what is regression analysis.
understand the purpose of regression analysis.
learn different types of regression analysis
Introduction
Regression analysis is the method that is most frequently used to address regression issues in
machine learning. It is based on data modelling and comprises choosing the line that fits the data
the best and travels the least distance between each data point while passing through all of the data
points. Although there are other regression analysis methods, logistic and linear regression are the
most frequently employed. In the end, the nature of the data will dictate the kind of regression
analysis model we use.
1. Linear Regression
Linear regression, which presumes a linear relationship between a dependent variable (Y) and
an independent variable (X), is the modelling technique that is most frequently utilised. It uses
a best-fit line, commonly referred to as a regression line. Y = c+m*X + e, where 'c' stands for the
intercept,'m' for the line's slope, and 'e' for the error term, is the formula for the linear
relationship.
One dependent variable and more than one independent variable can be used in a complex
linear regression model, which can be simple (just one dependent variable and one
independent variable).
2. Logistic Regression
The logistic regression method is appropriate when the dependent variable is discrete. In
other words, this method is used to determine the likelihood of events that are mutually
exclusive, such as pass/fail, true/false, 0/1, and so on. Thus, the probability has a value
between 0 and 1, the target variable has a range of two possible values, and its relationship
to the independent variable is depicted by a sigmoid curve.
3. Polynomial regression
In order to depict a non-linear relationship between dependent and independent variables,
polynomial regression analysis is performed. The best fit line is curved instead of straight in
this variation of the multiple linear regression model.
4. Ridge Regression
The ridge regression technique is used when the independent variables are highly
correlated and the data shows multicollinearity. Even if least squares estimates are
impartial in multicollinearity, their variances are high enough to induce a difference
between the observed value and the true value. By inflating the regression estimates, ridge
regression lowers standard errors.
The multicollinearity issue in the ridge regression equation is solved by the lambda ()
variable.
6. Quantile Regression
A part of the linear regression method is the quantile regression methodology. When the
conditions for linear regression are not met or when there are outliers in the data, it is
used. Quantile regression is used in statistics and econometrics.
A quick and effective method for covariance-based regression analysis is partial least squares
regression. It is beneficial for regression issues where there is a high likelihood of multicollinearity
between the variables. Regression is used once the procedure reduces the number of variables to a
reasonable number of predictors.
Example
Prediction of CO2 emission based on engine size and number of cylinders in a car.
The independent or predictor variable may be continuous or categorical for MLR, but the
dependent or target variable (Y) must be continuous/real.
Each feature variable needs to simulate the dependent variable's linear relationship.
A regression line is attempted to be fitted using MLR through a multidimensional space of data
points.
MLR Equation
The target variable (Y) in multiple linear regression is a linear mixture of several predictor variables
(x1, x2, x3,..., xn). The equation for multiple linear regression is as follows since it is an
improvement over simple linear regression:
Y= b<sub>0</sub>+b<sub>1</sub>x<sub>1</sub>+ b<sub>2</sub>x<sub>2</sub>+ b<sub>3
</sub>x<sub>3</sub>+...... bnxn ............... (a)
Where,
Y= Output/Response variable
# importing libraries
1. import numpy as nm
2. import [Link] as mtp
3. import pandas as pd
Bringing in a dataset Thedataset (50_CompList), which contains all the variables, will now be
imported. The code is as follows:
#importing datasets
1. data_set= pd.read_csv('50_CompList.csv')
Output: We will get the dataset as:
Figure 9 Dataset-dataframe
We can see from the output above that there are five variables, four of which are continuous and
one of which is a categorical variable.
Extracting dependent and independent Variables:
x= data_set.iloc[:, :-1].values
y= data_set.iloc[:, 4].values
Output
Figure 10 Output
The state column has been changed into dummy variables (0 and 1), as seen in the result shown
above. Each dummy variable column in this case corresponds to a single State. By contrasting it
with the original dataset, we can make sure. The first column represents the state of California, the
second column represents the state of Florida, and the third column represents the state of New
York.
Noted: It must be one less than the total number of dummy variables because we shouldn't use all
of them at once or else a dummy variable trap would be created.
The only piece of code we are writing right now is to avoid the dummy variable trap:
#avoiding the dummy variable trap:
x = x[:, 1:]
The model may become multicollinear if the initial dummy variable is not eliminated.
As shown in the output image up top, the first column has been eliminated.
The dataset will now be divided into a training set and a test set. Below is the code for this:
# Splitting the dataset into training and test set.
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test= train_test_split(x, y, test_size= 0.2, random_state=0)
Our dataset will be divided into a training set and a test set by the code above.
Output:The dataset will be divided into a training set and a test set by the aforementioned code. By
selecting the variable explorer option in Spyder IDE, you may view the output. The training set and
test set will resemble the illustration below:
regressor= LinearRegression()
[Link](x_train, y_train)
Output:
Out[9]: LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False)
We have now successfully used the training dataset to train our model. The performance of the
model will be evaluated using the test dataset in the following phase.
Figure 13 Output
We have the test set and the anticipated result set in the output shown above. By contrasting these
two values index by index, we may evaluate the performance of the model. As an illustration, the
first index has a predicted profit value of 103015 dollars and a test/real profit value of 103282
dollars. Since the difference is only 267 dollars, as predicted, our model is fully complete.
Additionally, we can look both the test and training dataset scores. The code is as follows:
print('Train Score: ', [Link](x_train, y_train))
print('Test Score: ', [Link](x_test, y_test))
Output: The score is:
Train Score: 0.9501847627493607
Test Score: 0.9347068473282446
According to the aforementioned score, our model is 93% accurate on the test dataset and 95%
correct on the training dataset.
Notably, we'll examine how applying the Backward Elimination procedure can help the model
perform better in the topic that follows.
Summary
Regression is a statistical analysis technique used to model the relationship between a
dependent variable and one or more independent variables
This type of regression models the relationship between a single independent variable and a
continuous dependent variable.
It involves modeling the relationship between multiple independent variables and a
continuous dependent variable.
It extends linear regression by introducing polynomial terms to capture nonlinear
relationships between variables.
Unlike linear regression, logistic regression is used when the dependent variable is categorical
or binary. It models the probability of an event occurring.
It is a regularization technique that adds a penalty term to linear regression to mitigate
overfitting and handle multicollinearity.
Similar to ridge regression, lasso regression also introduces a penalty term but uses L1
regularization. It can perform variable selection by shrinking some coefficients to zero.
Elastic net regression combines both L1 and L2 regularization (ridge and lasso) to address
multicollinearity and perform feature selection.
This type of regression is used when the data is collected over time and involves modeling the
relationship between variables with a temporal component.
Nonlinear regression models the relationship between variables using nonlinear functions. It
is useful when the data does not fit a linear model well.
It applies Bayesian statistical techniques to regression analysis, incorporating prior knowledge
and updating beliefs about the relationship between variables.
GLMs extend linear regression to handle different types of dependent variables, including
binary, count, and categorical data. Examples include Poisson regression and logistic
regression.
Robust regression techniques are designed to handle outliers and influential observations that
can significantly impact traditional regression models.
Keywords
Regression analysis: It is a statistical technique used to model the relationship between a
dependent variable and one or more independent variables.
Linear regression: It is a type of regression analysis where the relationship between the
dependent variable and independent variable(s) is assumed to be linear. It aims to find the
best-fit line that minimizes the differences between the observed data points and the predicted
values.
Multiple regression: It extends linear regression by considering multiple independent
variables to model the relationship with a dependent variable. It helps analyze how multiple
factors collectively influence the dependent variable.
Polynomial regression: It expands linear regression by introducing polynomial terms (e.g.,
quadratic, cubic) to capture nonlinear relationships between variables.
Logistic regression: Unlike linear regression, logistic regression is used when the dependent
variable is categorical or binary. It models the probability of an event occurring based on the
independent variables.
Ridge regression: It is a regularization technique that adds a penalty term (L2 regularization)
to linear regression to prevent overfitting and handle multicollinearity (high correlation
between independent variables).
Lasso regression: Similar to ridge regression, lasso regression adds a penalty term (L1
regularization) to linear regression. It can perform variable selection by shrinking some
coefficients to zero, effectively excluding them from the model.
Elastic net regression: Elastic net regression combines both L1 and L2 regularization (ridge
and lasso) to address multicollinearity and perform feature selection.
Time series regression: It is used when the data is collected over time, allowing for the
modeling of relationships between variables with a temporal component.
Nonlinear regression: Nonlinear regression models the relationship between variables using
nonlinear functions instead of assuming a linear relationship.
Bayesian regression: Bayesian regression applies Bayesian statistical techniques to
regression analysis, incorporating prior knowledge and updating beliefs about the
relationship between variables.
Generalized linear models (GLM): GLMs extend linear regression to handle different types
of dependent variables, including binary, count, and categorical data. Examples include
Poisson regression and logistic regression.
Robust regression: Robust regression techniques are designed to handle outliers and
influential observations that can significantly impact traditional regression models.
Dependent variable: Also known as the response variable, it is the variable being predicted
or explained by the independent variables in the regression model.
Independent variable: Also known as the predictor variable, it is the variable(s) used to
explain or predict the value of the dependent variable.
Coefficient: In regression analysis, coefficients represent the weights or slopes assigned to
the independent variables, indicating the strength and direction of their relationship with the
dependent variable.
Prediction: Regression models can be used to make predictions about the value of the
dependent variable based on the values of the independent variables.
Residuals: Residuals are the differences between the observed values of the dependent
variable and the predicted values by the regression model. They provide information about
the model's accuracy.
Overfitting: Overfitting occurs when a regression model fits the training data too closely,
capturing noise and random variations rather than the true underlying relationship. It may
result in poor performance when applied to new, unseen data.
Underfitting: Underfitting happens when a regression model is too simple and fails to
capture the underlying patterns and relationships in the data.
Multicollinearity: Multicollinearity refers to high correlation between independent
variables in a regression model. It can lead to instability in the coefficient estimates and makes
it challenging to interpret the individual effects of the variables.
Model selection: Model selection involves choosing the most appropriate regression model
among several candidate models based on various criteria such as goodness of fit, simplicity,
and interpretability.
Goodness of fit: Goodness of fit measures how well a regression model fits the observed
data. Common metrics include R-squared, which quantifies the proportion of variance
explained by the model.
R-squared: R-squared (coefficient of determination) is a statistical measure that represents
the proportion of variance in the dependent variable that can be explained by the independent
variables in the regression model. It ranges from 0 to 1, with higher values indicating a better
fit.
Adjusted R-squared: Adjusted R-squared is a modified version of R-squared that takes into
account the number of independent variables and adjusts for the degrees of freedom.
Cross-validation: Cross-validation is a technique used to assess the performance and
generalization ability of a regression model by splitting the data into training and testing
subsets.
Outliers: Outliers are data points that deviate significantly from the overall pattern in the
data. They can have a strong influence on the regression model and affect its results.
Homoscedasticity: Homoscedasticity refers to the assumption in regression analysis that the
variability of the residuals is constant across different levels of the independent variables.
Heteroscedasticity: Heteroscedasticity occurs when the variability of the residuals is not
constant across different levels of the independent variables. It can violate the assumptions of
linear regression.
Assumptions of regression: Regression analysis relies on certain assumptions, including
linearity, independence of errors, constant variance, absence of multicollinearity, and normal
distribution of residuals. These assumptions should be checked and met for reliable regression
results.
Self Assessment
1. Which type of regression analysis is suitable for predicting a continuous dependent variable
based on one or more independent variables?
A. Logistic regression
B. Polynomial regression
C. Multiple linear regression
D. Ridge
4. Which type of regression analysis is used when the dependent variable is categorical or
binary?
A. Polynomial regression
B. Logistic regression
C. Ridge regression
D. Simple linear regression
5. What is the purpose of regularization techniques, such as ridge regression and lasso
regression?
A. To handle outliers in the data
B. To reduce overfitting and improve model generalization
C. To select the most important independent variables
D. To address heteroscedasticity in the residuals
7. Which assumption in linear regression states that the residuals should follow a normal
distribution?
A. Linearity assumption
B. Independence assumption
C. Homoscedasticity assumption
D. Normality assumption
9. Which technique is used to evaluate the performance of a regression model on unseen data?
A. Cross-validation
B. Residual analysis
C. Outlier detection
D. Goodness-of-fit test
11. The objective of Linear Regression is to find the best-fit line that minimizes:
A. Regression problems
B. Classification problems
C. Clustering problems
D. Dimensionality reduction
15. Which evaluation metric is commonly used to assess the performance of Linear Regression
models?
A. Accuracy
B. F1-score
C. R-squared (R^2)
D. Area Under the Curve (AUC)
6. A 7. D 8. B 9. A 10. C
Review Questions
1. What is regression analysis, and what is its primary purpose?
2. Explain the difference between simple linear regression and multiple linear regression.
3. How does polynomial regression differ from linear regression? When is it useful?
10. What are the key assumptions of linear regression, and why are they important to
consider
Further Readings
[Link]
[Link]
[Link]/stable/modules/generated/sklearn.linear_model.[Link]
[Link]
[Link]
models/
Objectives
learn basic concepts about arrays and lists.
learn to differentiate between array and list.
learn several array creation routines in Numpy which are used to create Ndarray objects.
Introduction
When attempting to determine the relationship between two variables, the term regression is
[Link] link is employed in statistical modelling and machine learning to forecast how future
events will turn out.
Every data scientist should start by mastering linear regression, one of the original machine
learning methods. This straightforward model aids in our understanding of fundamental machine
learning ideas, such as identifying dependent and independent variables, developing models, and
comprehending the mathematics and statistics underlying models.
Using the statsmodel and sklearn libraries are the two most popular methods for creating linear
regression in Python. Both are excellent choices with advantages and disadvantages.
Model Evaluation: Evaluate the trained model's performance using various evaluation metrics.
Common metrics for linear regression include R-squared, mean squared error (MSE), and mean
absolute error (MAE). Calculate these metrics by comparing the predicted values to the actual
values from the testing dataset.
Interpretation of Coefficients: Analyse the coefficients of the linear regression model to
understand the relationship between the independent variables and the dependent variable.
Positive coefficients indicate a positive correlation, while negative coefficients indicate a negative
correlation. The magnitude of the coefficients represents the strength of the relationship.
Residual Analysis: Examine the residuals (the differences between the predicted and actual
values) to assess the model's goodness of fit. Plotting the residuals against the predicted values can
help identify patterns, such as heteroscedasticity or outliers.
Performance Visualization: Visualize the performance of the linear regression model using
appropriate graphs and plots. For example, you can create scatter plots to visualize the relationship
between the independent and dependent variables, or plot the predicted values against the actual
values.
Further Analysis: If necessary, you can explore additional aspects such as feature selection,
regularization techniques (e.g., ridge regression, lasso regression), or cross-validation to enhance
the model's performance or address specific requirements.
Performance Comparison: To assess the linear regression model's performance, you can compare
it with other regression techniques or variations of linear regression (e.g., polynomial regression).
This comparison can help determine the effectiveness and suitability of the linear regression
approach for your specific dataset.
Remember to interpret the results with caution and consider the assumptions of linear regression,
such as linearity, independence of errors, constant variance, and normal distribution of residuals.
Additionally, always cross-validate your findings and consider potential limitations or sources of
bias in the data.
Overall, implementing and analysing the performance of linear regression involves data
preparation, model training, evaluation, interpretation, and visualization. It is crucial to follow a
systematic approach and use appropriate evaluation metrics and visualization techniques to draw
meaningful conclusions from the analysis.
The size of the engine can be used to estimate a car's CO2 emissions, but multiple regression allows
us to include additional variables, such as the car's weight, to improve the prediction's accuracy.
import pandas
from sklearn import linear_model
df = pandas.read_csv("[Link]")
X = df[['Weight', 'Volume']]
y = df['CO2']
regr = linear_model.LinearRegression()
[Link](X, y)
#predict the CO2 emission of a car where the weight is 2300kg, and the volume is 1300cm3:
predictedCO2 = [Link]([[2300, 1300]])
print(predictedCO2)
Result
[107.2087328]
According to our calculations, a car with a 1.3-liter engine and a weight of 2300 kg emits about 107
grammes of carbon dioxide for every kilometre driven.
Coefficient
A quantity used to describe a relationship with an unknowable variable is called a coefficient.
For instance, if x is a variable, then 2x is x multiplied by 2. The coefficient is 2, and the unknown
variable is x.
We can request the weight and volume coefficient values against CO2 in this situation. The
response(s) we receive explain what would happen if one of the independent values was raised or
lowered.
import pandas
from sklearn import linear_model
df = pandas.read_csv("[Link]")
X = df[['Weight', 'Volume']]
y = df['CO2']
regr = linear_model.LinearRegression()
[Link](X, y)
print(regr.coef_)
Result
[0.00755095 0.00780526]
Result Explained
The weight and volume coefficient values are shown in the result array.
Volume: 0.00780526 Pounds Weight: 0.00755095
These numbers indicate that a weight gain of 1 kg will result in an increase in CO2 emissions of
0.00755095g.
Additionally, the CO2 emission rises by 0.00780526 g for every 1 cm3 increase in engine volume.
That's a good assumption, but let's put it to the test!
We have already estimated that the CO2 emission will be around 107g for a car with a 1300cm3
engine weighing 2300kg.
What happens if we add 1000 kg to the weight?
Copy the example from before, but change the weight from 2300 to 3300
import pandas
from sklearn import linear_model
df = pandas.read_csv("[Link]")
X = df[['Weight', 'Volume']]
y = df['CO2']
regr = linear_model.LinearRegression()
[Link](X, y)
predictedCO2 = [Link]([[3300, 1300]])
print(predictedCO2)
Result:
[114.75968007]
According to our calculations, a 3300 kg automobile with a 1.3 litre engine will emit about 115
grammes of carbon dioxide for every kilometre it travels.
import numpy as np
import [Link] as plt
%matplotlib inline
x = [Link](-5.0, 5.0, 0.1)
# You can adjust the slope and intercept
# to verify the changes in the graph
y = 2*(x) + 3
y_noise = 2 * [Link](size=[Link])
ydata = y + y_noise
# [Link](figsize =(8, 6))
[Link](x, ydata, 'bo')
[Link](x, y, 'r')
[Link]('Dependent Variable')
[Link]('Independent Variable')
[Link]()
We can now evaluate the non-linearity of the datasets and regressions after seeing an example of
linear regression. Create some data for quadratic regression, for example.
import numpy as np
import [Link] as plt
%matplotlib inline
x = [Link](-5.0, 5.0, 0.1)
# You can adjust the slope and intercept
# to verify the changes in the graph
y = [Link](x, 2)
y_noise = 2 * [Link](size=[Link])
ydata = y + y_noise
[Link](x, ydata, 'bo')
[Link](x, y, 'r')
[Link]('Dependent Variable')
[Link]('Independent Variable')
[Link]()
Let's now attempt to give our polynomial one more degree. This will give us a better idea of how
non-linear data actually seem in the real world.
import numpy as np
import [Link] as plt
%matplotlib inline
x = [Link](-5.0, 5.0, 0.1)
# You can adjust the slope and intercept
# to verify the changes in the graph
y = 1*(x**3) + 1*(x**2) + 1 * x + 3
y_noise = 20 * [Link](size=[Link])
ydata = y + y_noise
[Link](x, ydata, 'bo')
[Link](x, y, 'r')
[Link]('Dependent Variable')
[Link]('Independent Variable')
[Link]()
A model must have a nonlinear function of the parameters Theta, not necessarily the features X, in
order for it to be deemed nonlinear. The non-linear equation can take many different forms,
including exponential, logarithmic, logistic, and many others.
Summary
The regression chapter provides an overview of regression analysis, a statistical technique
used to model the relationship between a dependent variable and one or more independent
variables. The chapter covers various types of regression models and their applications in
different scenarios.
The chapter begins with an introduction to regression analysis, emphasizing its purpose in
understanding and predicting relationships between variables. It explains the key concepts of
dependent and independent variables and introduces the idea of fitting a regression model to
data.
Different types of regression models are discussed in the chapter. Simple linear regression is
presented as the basic form, where a single independent variable is used to predict a
continuous dependent variable. Multiple linear regression extends this concept by
incorporating multiple independent variables.
The chapter also explores polynomial regression, which allows for nonlinear relationships by
introducing polynomial terms. Logistic regression is introduced as a technique for modeling
categorical or binary dependent variables.
Regularization techniques, such as ridge regression and lasso regression, are covered to
address issues like multicollinearity and overfitting. The concept of feature selection and its
importance in regression analysis are explained.
Assumptions of linear regression are discussed, including linearity, independence of errors,
constant variance, and normal distribution of residuals. Violations of these assumptions can
affect the accuracy and reliability of regression models.
The chapter emphasizes the importance of model evaluation and interpretation. Evaluation
metrics, such as R-squared, mean squared error (MSE), and mean absolute error (MAE), are
introduced to assess the model's performance. Residual analysis and visualizations are
discussed as tools for understanding the model's fit to the data.
Throughout the chapter, practical implementation aspects, such as data preparation, training
the model, and interpreting the coefficients, are highlighted. Considerations for addressing
outliers, heteroscedasticity, and multicollinearity are also covered.
The chapter concludes by emphasizing the need for careful interpretation, cross-validation,
and consideration of potential limitations and biases in the data. It highlights the importance
of comparing regression models and exploring additional techniques to enhance performance
and meet specific requirements.
Overall, the regression chapter provides a comprehensive overview of regression analysis,
from the basic concepts to advanced techniques, highlighting their applications and
considerations for implementation and interpretation.
Keywords
Regression analysis: A statistical technique used to model the relationship between a
dependent variable and one or more independent variables. It aims to understand and predict
the behavior of the dependent variable based on the independent variables.
Linear regression: A type of regression analysis where the relationship between the
dependent variable and independent variable(s) is assumed to be linear. It finds the best-fit
line that minimizes the differences between the observed data points and the predicted
values.
Multiple regression: A regression analysis technique that involves modeling the
relationship between a dependent variable and multiple independent variables. It helps
analyze how multiple factors collectively influence the dependent variable.
Polynomial regression: A regression model that extends linear regression by introducing
polynomial terms (e.g., quadratic, cubic) to capture nonlinear relationships between variables.
It can better fit data that doesn't follow a linear pattern.
Logistic regression: A type of regression used when the dependent variable is categorical or
binary. It models the probability of an event occurring based on the independent variables. It
is commonly used for classification problems.
Ridge regression: A regularization technique that adds a penalty term (L2 regularization) to
linear regression. It helps mitigate overfitting and handles multicollinearity, which occurs
when there is high correlation between independent variables.
Lasso regression: A regularization technique that adds a penalty term (L1 regularization) to
linear regression. It performs variable selection by shrinking some coefficients to zero,
effectively excluding them from the model. It can help with feature selection.
Elastic net regression: A regression technique that combines both L1 and L2 regularization
(ridge and lasso) to handle multicollinearity and perform feature selection. It offers a balance
between the two regularization approaches.
R-squared: A statistical measure that represents the proportion of variance in the dependent
variable that can be explained by the independent variables in a regression model. It ranges
from 0 to 1, with higher values indicating a better fit.
Cross-validation: A technique used to evaluate the performance and generalization ability
of a regression model by splitting the data into training and testing subsets. It helps assess
how well the model performs on unseen data.
Homoscedasticity: An assumption in regression analysis that refers to equal variances of the
residuals (differences between predicted and actual values) across different levels of the
independent variables. It implies a consistent spread of errors.
Assumptions of regression: These are the underlying assumptions in regression analysis
that need to be met for reliable results. They include linearity, independence of errors,
constant variance of residuals, absence of multicollinearity, and normal distribution of
residuals.
Self Assessment
1. What type of relationship does linear regression model between the dependent variable (Y)
and the independent variable (X)?
A. Linear
B. Quadratic
C. Exponential
D. Logarithmic
3. Which method is commonly used to find the best-fitted line in linear regression?
A. Gradient Descent
B. K-Means
C. Hierarchical Clustering
D. Mean Shift
4. In non-linear regression, the relationship between the dependent variable (Y) and the
independent variable(s) (X) can be modeled as:
A. Straight line
B. Curve
C. Hyperplane
D. Exponential function
5. Which of the following is a common approach to finding the best-fitted curve in non-linear
regression?
A. Ordinary Least Squares (OLS)
B. Gradient Descent
C. Logistic Regression
D. Akaike Information Criterion (AIC)
7. What is the key difference between linear regression and multiple regression?
A. Linear regression has one dependent variable, and multiple regressions have multiple
dependent variables.
B. Linear regression can handle non-linear relationships, while multiple regression cannot.
C. Multiple regression has multiple independent variables, while linear regression has only
one.
D. There is no difference; they are the same.
10. Which of the following types of regression is suitable for predicting a binary outcome?
A. Linear regression
B. Multiple regression
C. Logistic regression
D. Polynomial regression
11. In simple linear regression, the relationship between the dependent variable (Y) and the
independent variable (X) is modeled as:
A. Y = a + bX
B. Y = aX^2 + bX + c
C. Y = aX + b
D. Y = a^X + b
12. What is the main objective of the Ordinary Least Squares (OLS) method in regression?
A. Minimize the sum of absolute errors
B. Minimize the sum of squared errors
C. Maximize the correlation coefficient
D. Maximize the R-squared value
13. When evaluating a regression model, what does the R-squared value represent?
A. The accuracy of the model's predictions
B. The percentage of variance in the dependent variable explained by the independent variable
C. The p-value of the regression coefficients
D. The number of data points in the dataset
14. Which technique can be used to handle multicollinearity in multiple linear regression?
A. Drop one of the independent variables causing multicollinearity
B. Combine the correlated independent variables into one variable
C. Perform feature scaling on the independent variables
D. Use regularization techniques like Ridge or Lasso regression
1. A 2. A 3. A 4. B 5. B
6. B 7. C 8. C 9. C 10. C
Review Questions
1. Discuss the significance of evaluating the performance of a linear regression model. What
are some commonly used evaluation metrics for assessing its performance?
2. Explain the concept of multicollinearity in the context of multiple regression. How does
multicollinearity affect the interpretation of the regression coefficients?
3. Compare and contrast the performance evaluation process for linear regression and
multiple regression models. What additional factors need to be considered in multi-
regression analysis?
4. What are the main limitations of linear regression when dealing with non-linear
relationships between variables? How can non-linear regression models address these
limitations?
5. Describe the process of assessing the goodness of fit for a non-linear regression model.
What specific evaluation metrics and techniques can be used for non-linear regression
performance analysis?
6. Discuss the importance of examining residual plots in the performance analysis of
regression models. How can these plots help identify potential issues or violations of
regression assumptions?
7. Explain the concept of overfitting in the context of regression analysis. How does
overfitting affect the performance of a regression model, and what techniques can be used
to mitigate it?
8. Describe the steps involved in comparing the performance of different regression models.
What are some criteria and techniques that can be used to select the best model?
9. Discuss the assumptions underlying the performance analysis of linear regression models.
Why is it important to assess and meet these assumptions before drawing conclusions
from the analysis?
10. Explain the role of cross-validation in the performance analysis of regression models. How
can cross-validation help in assessing a model's ability to generalize to new, unseen data?
Further Readings
Madan Gopal, Applied Machine Learning, McGraw Hill Education, India, 2018.
S. N. Sivanandam, S.N. Deepa, Principles Of Soft Computing, Wiley Publications,
Second Edition, 2011.
Rajasekaran, S., Pai, G. A. Vijayalakshmi, Neural Networks, Fuzzy Logic and Genetic
Algorithm Synthesis And Applications, Prentice Hall of India, 2013.
N. P. Padhy, S. P. Simon, Soft Computing With Matlab Programming, Oxford
University Press, 2015.
Unit 07:Classification
CONTENTS
Objectives
Introduction
7.1 Introduction to Classification Problems
7.2 Decision Boundaries
7.3 Dataset
7.4 K-Nearest Neighbours ( k-NN )
7.5 Decision Tree
7.6 Building Decision Tree
7.7 Training and visualizing a Decision Tree
Summary
Keywords
Self Assessment
Answers for Self Assessment
Review Questions
Further readings
Objectives
Understanding the classification problems and types of classification.
Understanding the different parameters for building decision trees.
Understanding the concepts of k-Nearest neighbours algorithm.
Understanding the difference between decision tree and random forest.
Understanding the fundamentals of decision boundaries.
Introduction
In this unit, we will study k-Nearest Neighbors algorithm and Decision Tree Algorithmfor the
classification problems. We will understand how the classification problems will be handled along
with types of classification. Dataset preparation is one of the very important aspects for machine
learning, which is already covered in the previous units, is also highlighted [Link] this unit, we
focus more on decision boundaries and building the decision trees including training and testing.
The concepts of linearly separable data and non-linearly separable data is discussed in a simplest
wary. Examples are given whenever it is needed for the explanation. Similarly, K-Nearest
Neighbors algorithm is also discussed thoroughly. Let us see one by one.
and feature engineering can be helpful to convert the data into the format that machine learning
algorithm understands the [Link] that the data is ready for classification and proceed
further.
Classification is categorized into two types based on the number of ways the data can be classified,
which are binary classification and multiclass classification.
Binary Classification
This has only two class [Link] input data is classified into two [Link] example, as per our
previous discussion, let us assume the class labels ‘two-wheelers’ and ‘not two-wheelers’. The
machine learning algorithm has knowledge about only one thing that is ‘two-wheelers’. The
outcome will be either YES or [Link] gives YES if the given data is about two-wheelers and
gives NO if the given data is not about two-wheelers. Training Data and testing data are used to
train the machine and used to check the efficiency of the trained machine respectively.
Multiclass Classification
This type of classification is having more than two class labels as shown in figure [Link] training
data should be prepared accordingly. The machine will be having knowledge about multiple
things. Figure 2 and 3 is explaining the concepts and an example to demonstrate the multiclass
classification.
7.3 Dataset
We use the readymade dataset from the website “UC Irvine Machine Learning Repository”. This is
used for the education purpose only. Majority of the machine learning tasks can be performed with
the available datasets from the given repository. The link is given at the end of this document. And,
the dataset from Kaggle platform is also another option for you for practice. Image processing
subject knowledge is needed to handle image data. Video processing subject knowledge is needed
to handle video data. Signal processing subject knowledge is needed to handle voice data. Natural
Language Processing subject knowledge is needed to handle text data. The term ‘data’ is a generic
thing. The domain knowledge and the knowledge to handle the given data are very much required
to perform any classification task.
class with the most number of votes among the k neighbors is selected. If k=1, then it is usually not
sufficient for determining the class of ‘x’ due to noise and outliers in the data. A set of nearest
neighbors is needed to accurately decide the class. The category computation of a new data point is
shown in Figure 5. It depends on how many data points are near to the new data point. The
majority of the category will be the category of this new point as shown in Figure 5.
The key issue of k-NN algorithm is the distance function or similarity function, which is selected on
the basis of applications and nature of the data. The cautious selection of an appropriate distance
function is a crucial step in the use of k-NN. Another crucial thing is to select the number of
neighbors. This relies heavily on the problem being solved, as the number is dependent on the data
distribution. This needs investigation of varying numbers of neighbors and end up with an optimal
number with the help of validation set. The training set also should be given more focus by
ensuring whether data set has enough examples of all possible categories. It should be a balanced
training [Link], it is recommended to have an odd number for k to avoid ties in classification,
and cross-validation tactics can help you choose the optimal k for your dataset.
Nodes
Edges / branches
Leaves
Entropy
Information Gain
Gini Index
You can refer the textbook [Madan Gopal, Applied Machine Learning, McGraw Hill Education,
India, 2018] for the computation.
Summary
Understood the classification problems and types of classification.
Understood the different parameters for building decision trees.
Understood the concepts of k-Nearest neighbours algorithm.
Understood the difference between decision tree and random forest.
Understood the fundamentals of decision boundaries.
Keywords
Classification
k-Nearest Neighbours
Decision Tree
Distance Metrics
Self Assessment
1. Which of the following will be Euclidean Distance between the two data point A(1,3) and
B(2,3)?
A. 8
B. 4
C. 2
D. 1
2. Machine learning algorithms build a model based on the sample data known as ______.
A. Training Data
B. Transfer Data
C. Validation Data
D. Test Data
3. In k-NN, what will happen when you decrease / increase the value of k?
A. Smoothness of boundary doesn’t dependent on value of K
10. k-NN algorithm does more computation on test time rather than train time.
A. True
B. False
13. ___________ refers to a model that can neither models the training data nor generalizes to
new data.
A. Goodfitting
B. Overfitting
C. Underfitting
D. Allof the above
14. “Decision Tree can be used for classification and regression problems”. Justify the given
statement.
A. True
B. False
6. A 7. C 8. B 9. A 10. A
Review Questions
1. Explain the different types of classification with examples.
2. List the various distance metrics used in k-NN.
3. Explain the process of designing a decision tree with an example.
4. Explain in detail about the selection of best node.
5. Highlight the important things about Entropy, Information Gain and Gini Index.
Further readings
MadanGopal, Applied Machine Learning, McGraw Hill Education, India, 2018.
S. N. Sivanandam, S.N. Deepa, Principles Of Soft Computing, Wiley Publications,
Second Edition, 2011.
Rajasekaran, S., Pai, G. A. Vijayalakshmi, Neural Networks, Fuzzy Logic and Genetic
Algorithm Synthesis And Applications, Prentice Hall of India, 2013.
N. P. Padhy, S. P. Simon, Soft Computing With Matlab Programming, Oxford
University Press, 2015.
Web Links
[Link]
[Link]
[Link]
[Link]
[Link]
Dr. Rajni Bhalla, Lovely Professional University Unit 08: Classification Algorithms
Objectives
1. Understanding the classification problems and types of classification.
2. Understanding how the SVM is used for classification.
3. Understanding the concepts of higher dimensional space used in SVM.
4. Understanding the different types of kernels in detail.
5. Understanding the logistic regression and its implementation.
Introduction
In this unit, we will study two important algorithms especially on the classification perceptive.
They are Logistic regression algorithm and support vector machine algorithm. We will understand
how the classification problems will be handled along with types of classification. Also, Dataset
preparation is one of the very important aspects for machine learning, which is already covered in
the previous units, is also [Link] the data is provided to logistic regression and support
vector machine is given in more [Link] fundamental concepts of SVM, in particular, the
concepts of hyperplane and margin are discussed here along with different types of kernels in
SVM. Examples are given whenever it is needed for the explanation. Let us explore one by one.
size of the training data is very less, then Machine learning algorithm will learn too much and it
can’t be able to understand the new data. Hence, it will fail which is known as overfitting issues.
Also note here that variance is high. Similarly, when the size of the training data is too much, then
Machine learning algorithm will not able to learn properly. This will lead to the failure of machine
learning algorithm, whichis known as under fitting issues. Note that bias is high here.
8.2 Dataset
We use the ready-made dataset from the website “UC Irvine Machine Learning Repository”. This is
suggested for the education purpose only. Majority of the machine learning tasks can be performed
with the available datasets from the given repository. The link is given at the end of this document.
Home page of the site is given in Figure 2. And, the dataset from Kaggle platform is also another
option for you for practice. Image processing subject knowledge is needed to handle image data.
Video processing subject knowledge is needed to handle video data. Signal processing subject
knowledge is needed to handle voice data. Natural Language Processing subject knowledge is
needed to handle text data. The term ‘data’ is a generic thing. The domain knowledge and the
knowledge to handle the given data are very much required to perform any classification task.
Linear Regression
Logistic Regression
The following diagram will give you an idea on the working model how it looks like. Linear
regression is usually used for regression problems. For example, we can try to predict the gold
price after 5 years based on the previous 25 years of data. This problem is the popular example for
regression. Similarly, prediction may be done in agricultural yield prediction, population
prediction, average income per person and [Link] said prediction problemsare possible in the
regression, with the help of the previous data. If previous data is correct then the prediction will be
correct. In the sense that, we should take at most care in data collection. Logistic regression
algorithm is used for the classification problems. Both are of supervised algorithms. Both the
algorithms are using two terminologies, i.e., dependent variable and independent variable as in
Figure 3. Linear regression analysis is used to predict the value of a variable based on the value of
another variable. The variable you want to predict is called the dependent variable. The variable
you are using to predict the other variable's value is called the independent [Link] are three
types of logistic regression models, which are defined based on categorical response. They are
discussed below.
As we already mentioned, the linear regression model is used for regression problems. These
regression concepts are understood by this time. We will look at the different types of regression
models as below.
Line regression
Look at the figure 4. Let us assume that all the blue colored points are previously collected data on
the specific domainuptothe year 2022. I want to know, how the data will be for the year 2030.
Simply, forecasting the values based on the presented or given data. The goal is to predict the value
of a dependent variable based on independent [Link] Squares Method is used as Metric to
select the good regression line for the given data as shown in Figure 5 and Figure 6. Figure 5 is
looking for the optimal regression line, which will best fit the given data and the orientation. We
need to check multiple options or multiple lines to conclude the better one.
Polynomial Regression
Polynomial Regression is a regression algorithm that models the relationship between a dependent
and independent variables as nth degree polynomial. The model is given in the Figure 8.
Kernels are using higher dimensional space for effective classification as shown in Figure 11.
Linear Kernel
Linear Kernel is used when the data is Linearly separable, that is, it can be separated using a single
Line. It is one of the most common kernels to be used.
classifier = SVC(kernel ='linear')
Polynomial Kernel
This function can be used as per the syntax given below using Python.
classifier = SVC(kernel ='poly', degree = 4)
Summary
Understood the classification problems and different types of classification.
Discussed the difference between regression and classification.
The basic concepts of logistic algorithm with an example are discussed.
The fundamentals of support vector machinealgorithm along with their margin, hyperplane,
support vectors are explained with examples.
Keywords
Classification
Kernel
Support Vector Machines
Logistic Regression
Hyperplane
Margin
Self Assessment
1. Logistic regression is used when you want to ____________.
A. Predict a continuous variable from dichotomous variables.
B. Predict any categorical variable from several other categorical variables.
C. Predict a continuous variable from dichotomous or continuous variables.
D. Predict a dichotomous variable from continuous or dichotomous variables.
2. Machine learning algorithms build a model based on the sample data known as ______.
A. Training Data
B. Transfer Data
C. Validation Data
D. Test Data
A. Clustering
B. Unsupervised Machine Learning
C. Supervised Machine Learning
D. Reinforcement learning
6. _________ the target variable can have three or more possible values without any order.
A. Multinomial Logistic Regression
B. Binary Logistic Regression
C. Ordinal Logistic Regression
D. All of the above
11. Support vectors are the data points that lie closest to the decision surface.
A. TRUE
B. FALSE
12. Which of the following are real world applications of the SVM?
A. Text and Hypertext Categorization
B. Image Classification
C. Clustering of News Articles
D. All of the above
13. ___________ refers to a model that can neither models the training data nor generalizes to
new data.
A. Goodfitting
B. Overfitting
C. Underfitting
D. Allof the above
14. Maximizing the distances between nearest data point and hyper plane will help us to
decide the right hyper-plane is related to _______.
A. Margin
B. Mercer’s Theorem
C. Regression
D. None of these
15. Which of the following can only be used when training data are linearly separable?
A. The centroid method
B. Linear Logistic Regression
C. Linear Soft margin SVM
D. Linear hard-margin SVM
6. A 7. C 8. B 9. A 10. A
Review Questions
1. Explain the different types of classification with examples.
2. What do you understand by the concept of hyperplane and margin?
3. Describe and explain the process of kernels in SVM.
4. Explain in detail about the decision tree classifier.
5. Highlight the important things about random forest classifier.
Further Readings
MadanGopal, Applied Machine Learning, McGraw Hill Education, India, 2018.
S. N. Sivanandam, S.N. Deepa, Principles Of Soft Computing, Wiley Publications,
Second Edition, 2011.
Rajasekaran, S., Pai, G. A. Vijayalakshmi, Neural Networks, Fuzzy Logic and
Genetic Algorithm Synthesis And Applications, Prentice Hall of India, 2013.
N. P. Padhy, S. P. Simon, Soft Computing With Matlab Programming, Oxford
University Press, 2015.
Web Links
[Link]
[Link]
[Link]
[Link]
[Link]
Objectives
To understand the classification problems.
To implement the K-Nearest Neighbours Algorithm for classification problems.
To implement the Support Vector Machine Algorithm for classification problems.
To understand the usages of different kernels in Python Code.
To implement the logistic regression algorithm for classification problems.
Introduction
Many machine-learning algorithms are available for performing classification tasks not only binary
classification but also multiclass classification. Few are, Logistic Regression, k-Nearest Neighbors,
Decision Trees, Support Vector Machines, Naïve Bayes, Random forest and Artificial Neural
Networks. In this unit, we will try to understand k-nearest neighbor algorithm, support vector
machine algorithm and logistic regression algorithm in detail. The above-mentioned algorithms
will be implemented using python language. The programs are also given in this section one by one
with outcome of each execution. Let us explore one by one.
9.1 Datasets
We use the ready-made dataset from the website “UC Irvine Machine Learning Repository” as in
Fig [Link] are going to use Iris Dataset as in the Fig 2 for our implementation. At the same time, you
can also try with some other datasets as in Fig 3 and Fig 4. You can download those datasets and
use it in the python program. Otherwise, you can refer the web link directly in the python [Link]
will read the data directly.
Summary
Understood how to read the iris dataset directly using web-link.
We have implemented K-Nearest Neighbour Algorithm and the performance was 91%.
Support Vector Machine algorithm is implemented and the accuracy was 96%.
Radial basis function was used in SVM as the kernel function for the implementation.
Thelogistic regression algorithm gave the performance of 96%.
Thedataset is preprocessed with Standard Scaler function and the same is used for training
and testing.
Keywords
Classification
Kernel
Support Vector Machines
Logistic Regression
Hyperplane
Margin
Self Assessment
Q1) Logistic regression is used when you want to ____________ .
Q2) Machine learning algorithms build a model based on the sample data known as ______.
A. Training Data
B. Transfer Data
C. Validation Data
D. Test Data
A. Clustering
B. Unsupervised Machine Learning
C. Supervised Machine Learning
D. Reinforcement learning
A. 1
B. 2
C. 3
D. 4
Q6) _________ the target variable can have three or more possible values without any order.
A Classification
B Reinforcement
C Supervised
D Unsupervised
Q8) Linear regression assumes that the data follows a linear function; Logistic regression
models the data using the _________.
A Linearfunction
B Sigmoidfunction
C Continues function
D Samplefunction
Q11) Support vectors are the data points that lie closest to the decision surface.
A. True
B. False
Q12) Which of the following are real world applications of the SVM?
Q13) ___________ refers to a model that can neither models the training data nor generalizes to
new data.
A. Goodfitting
B. Overfitting
C. Underfitting
D. Allof the above
Q14) Maximizing the distances between nearest data point and hyper plane will help us to
decide the right hyper-plane is related to _______.
A. Margin
B. Mercer’s Theorem
C. Regression
D. None of these
Q15) Which of the following can only be used when training data are linearly separable?
6. A 7. C 8. B 9. A 10. A
Review Questions
1. Whatis binary classification and multi-class classification? Giveexamples.
2. How do you access the standard datasets directly from sklearn library?
3. Describe the outputs of SVM algorithm when you use different kernels such as linear or
polynomial.
4. Explain the preprocessing techniques required while using Breast Cancer Dataset.
5. Comment on the challenges faced when you use Algerian Forest Fires Datasets with
respect to KNN, SVM and Logistic Regression algorithm.
Further Readings
MadanGopal, Applied Machine Learning, McGraw Hill Education, India, 2018.
S. N. Sivanandam, S.N. Deepa, Principles Of Soft Computing, Wiley Publications,
Second Edition, 2011.
Rajasekaran, S., Pai, G. A. Vijayalakshmi, Neural Networks, Fuzzy Logic and Genetic
Algorithm Synthesis And Applications, Prentice Hall of India, 2013.
N. P. Padhy, S. P. Simon, Soft Computing With Matlab Programming, Oxford
University Press, 2015.
Web Links
[Link]
[Link]
[Link]
[Link]/stable/modules/generated/[Link]
[Link]
[Link]/stable/modules/generated/sklearn.linear_model.[Link]
Unit 10:Clustering
CONTENTS
Objectives
Introduction
10.1 Introduction to Clustering
10.2 K-Means Algorithm
10.3 Mathematical Model of K-Means
10.4 Hierarchical Clustering
10.5 Types of Hierarchical Clustering
10.6 Linkage Methods
Summary
Keywords
Self Assessment
Answers for Self Assessment
Review Questions
Further Readings
Objectives
1. Understanding the fundamental concepts of clustering.
2. Understanding the working style ofK-Means Algorithms.
3. Understanding thelinkage methods used for hierarchical clustering.
4. Understanding in detail about types ofHierarchical algorithm.
5. Understanding the mathematical model of the clustering algorithms.
Introduction
In this unit, the basic concepts of clustering are discussed with necessary examples. This section
introduces the popular clustering algorithm known as K-Means Clustering Algorithm in detail. The
mathematical model of the algorithm is discussed along with different distance metrics used for
computation of distances between the points. In the same way, the different types of clustering is
also considered and discussed with examples. In particular, hierarchical clustering is focused at the
best along with the linkage methods, which is very important for hierarchical clustering
mechanisms.
data are called clusters. The example is given in figure 1, where the data is grouped in three
different clusters. All the clusters are encircled for a kind of representation.
Clustering is very much important as it determines the intrinsic grouping among the
unlabeleddata. There is no specific criteria or condition to perform good clustering. It depends on
the user and their requirements. In the next section, we introduce the K-Means clustering
algorithm, which is commonly used by the academic and research community.
Euclidean Distance
Manhattan Distance
The above two methods are commonly used to calculate distance. The formula is shown and
explained in the following figure 3.
(1)
and then the sum of squared errors is defined by as given in (2) where k stands for number of
clusters.
(2)
Agglomerative
Divisive
Single Linkage
Complete Linkage
Centroid Linkage
Average Linkage
Single linkage calculates the minimum distance between clusters. This measure takes into
consideration of only the two nearest members of a pair of clusters. This procedure or process is
sensitive to outliers. Complete linkage calculates the maximum distance between the clusters. The
centroid linkage calculates the distance between the centroids of each of two clusters. The average
linkage calculates the average distance of all the possible distances between the clusters.
Summary
Understood the fundamental concepts of clustering.
Keywords
Clustering
Euclidean distance
Manhattan distance
Hierarchical clustering
Agglomerative model
Divisive model
Linkage methods
Self Assessment
1. The independent variable is also called __________.
A Regressor
B Regressand
C Predictand
D Estimated
5. Identify the best method that is used for finding optimal clusters in k-means algorithm.
A. Euclidean method
B. Manhattan method
C. Elbow method
D. Silhouette method
10. Justify the statement. “Divisive Clustering is not the hierarchical clustering methods”.
A True
B False
13. Which of the following clustering algorithm requires the number of clusters to be pre-
specified?
A hierarchical clustering
B k-means clustering
C DBSCAN
D Markov clustering algorithm
A. Top down
B. Bottom up
C. Down up
D. None of these
15. __________methods have good accuracy and ability to merge two clusters.
A. Density-Based
B. Hierarchical Based
C. Grid-based
D. None of these
6. B 7. B 8. A 9. D 10. B
Review Questions
1. Explain the computation of various distance metrics.
2. What do you understand by the concept of dendrogram?
3. Differenciate agglomerative and divisive hierarchical clustering.
4. Mention any two applications of clustering algorithms.
5. Explain the different linkage methods with examples.
Further Readings
MadanGopal,Applied Machine Learning, McGraw Hill Education, India, 2018.
S. N. Sivanandam, S.N. Deepa, Principles Of Soft Computing, Wiley Publications,
Second Edition, 2011.
Rajasekaran, S., Pai, G. A. Vijayalakshmi, Neural Networks, Fuzzy Logic and Genetic
Algorithm Synthesis And Applications, Prentice Hall of India, 2013.
N. P. Padhy, S. P. Simon, Soft Computing With Matlab Programming, Oxford
University Press, 2015.
Web Links
[Link]
[Link]
[Link]
[Link]
[Link]
machine-learning/
Objectives
Understanding the basics of ensemble methods.
Understanding the concept of bagging.
Understanding the structure of random forests.
Understanding the difference between the decision tree and random forests.
Understanding the working style of random forests.
Introduction
Ensemble learning methods are made up of a set of classifiers. All the output of each classifier will
be taken and are aggregated to produce a final result. The most well-known ensemble methods are
bagging or bootstrap aggregation and boosting. These methods are commonly used to reduce the
variance within a noisy dataset. They are explained in detail with necessary examples. Finally, the
concepts of random forest are explained with the working procedure. Also, we can understand the
difference between the random forest and decision [Link] units will emphasis the importance
of ensemble learning over machine learning algorithms.
Machine Learning
the case of regression problems, the average or weighted average is computed. We will be having
the difference in parameter values in each ML algorithm is because of the fact that their training
patterns differ and each one handles a certain percentage of data accuracy. In the bagging
technique, individual approaches are constructed separately. But, in boosting technique, each new
model is impacted by the performance of those built earlier. In boosting, we first make a model
with accuracy on the training set greater than average. And then add new component classifiers to
make an ensemble whose joint decision rule possesses a high level of accuracy on the training set.
AdaBoost or Adaptive Boosting is a widely used algorithm for boosting. Ensemble structure is
shown in Figure 1 for better understanding.
11.2 Bagging
Basically, creating a different training subset from sample training data with replacement is called
Bagging. The final output is based on majority [Link] is also known as Bootstrap Aggregation.
The distribution of data is given in the Figure 2 below.
11.3 Boosting
Boosting is a method used to reduce the predictive errors in machine learning. Boosting actually
tries to overcome this issue by training multiple machine learning models sequentially to improve
the accuracy of the overall system. Performance of the machine learning model improves since the
model is created using multiple weak learners into a single learning model. We can also say that
“The final model is created by combing weak learners into strong learners by creating sequential
models and it has the highest accuracy is called Boosting. Example: ADA BOOST, XG BOOST.
Let us discuss what is weak learners and strong learners. Weak learners have low prediction
accuracy and it is similar to random guessing. They will have overfitting issues. So, they can’t
classify the data, which varies too much from the original dataset. If we train the model to identify
the “Cat” as animal, which has pointed ears, but it will fail to recognize a “Cat” whose ears are
curled. Strong learners have higher prediction accuracy. This converts a system of weak learners
into a strong learning system. Let us consider an example, to identify the “Cat” image, it combines
a weak learner that guesses for pointy ears and another learner that guesses for cat-shaped eyes.
The overall accuracy of the system improves since the learners analyze all the properties
individually.
Usually, the decision trees are used for boosting implementations. Decision trees are data structures
in machine learning that works by dividing the dataset into smaller and smaller datasets based on
their features. We know that bagging and boosting are the two common ensemble methods used to
improve the prediction [Link], the main difference lies in the method of [Link]
difference between the bagging and boosting is understood from the figure 3 given below.
Machine Learning
Step 3
The algorithm passes the weighted data to the next decision tree.
Step 4
The algorithm repeats the steps from 2 to 3 until the instances of training errors are below a certain
threshold.
Also, the boosting has few types of it. They are adaptive boosting, gradient boosting and extreme
gradient boosting. Let us see what are theymean.
Adaptive boosting
It is one of the earliest boosting models. It adapts and tries to self-correct in every iteration of the
boosting process. Initially adaptive boosting gives the same weights to each dataset. Then it
automatically adjusts the weights of the data points after every decision tree. It gives more weights
to incorrectly classified items to correct them for the next iteration. It repeats the process until the
residual error or the difference between actual and predicted values, falls below an acceptable
threshold. We can also use AdaBoost with many predictors and it is typically not as sensitive as
other boosting algorithms. This approach does not work well when there is a correction among
features or high data dimensionality. AdaBoost is a suitable type of boosting for classification
problems.
Gradient Boosting
It is similar to AdaBoost but it has sequential training technique. The difference between the
AdaBoost and gradient boosting is that gradient boosting does not give incorrectly classified items
the more weight. Instead, gradient boosting optimizes the loss function by generating base learners
sequentially so that the present base learner is always more effective than the previous one. This
method attempts to generate accurate results initially instead of correcting errors throughout the
process, like AdaBoost. Gradient boosting can help with both classification and regression based
problems.
Machine Learning
path = "[Link]
headernames = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'Class']
dataset = pd.read_csv(path, names = headernames)
[Link]()
X = [Link][:, :-1].values
y = [Link][:, 4].values
y_pred = [Link](X_test)
print(result)
result1 = classification_report(y_test, y_pred)
print("Classification Report:",)
print (result1)
result2 = accuracy_score(y_test,y_pred)
print("Accuracy:",result2)
There are key benefits and challenges from random forest algorithm as follows.
Few Benefits:
Time consuming process: Since random forest algorithms can handle large data sets, they can
be providing more accurate predictions, but can be slow to process data as they are computing
data for each individual decision tree.
Requires more resources: Since random forests process larger data sets, they will require more
resources to store the data.
Complexity: The prediction of a single decision tree is easier to interpret when compared to a
forest of them.
Summary
This unit discussed about ensemble learning methods that were made up of a set of classifiers. All
the output of each classifier were taken and were aggregated to produce the final result. The most
well-known ensemble methods were bagging or bootstrap aggregation and boosting. These
methods were commonly used to reduce the variance within a noisy dataset. They were explained
in detail with necessary examples. The types of boosting were also highlighted in this unit. Finally,
the concepts of random forest were explained with the working procedure. Also, we understood
the difference between the random forest and decision trees. These units emphasized the
importance of ensemble learning over machine learning algorithms in all the possible ways.
Machine Learning
Keywords
Bagging
Random Forest
Decision Tree
Boosting
Self Assessment
1. What is true about an ensemble classifier? 1. Classifiers that are more “sure” can vote with
more conviction. 2. Classifiers can be more “sure” about a particular part of the space. 3.
Most of the times, it performs better than a single classifier.
A. 1 and 2
B. 1 and 3
C. 2 and 3
D. All of the above
5. In ________the output class is the prediction based on the average of probability given to
that class.
A. Hard voting
B. Soft voting
C. Both A and B
D. None of these
11. In random forest or gradient boosting algorithms, features can be of any type. For
example, it can be a continuous feature or a categorical feature. Which of the following
option is true when you consider these types of features?
A. Only Random forest algorithm handles real valued attributes by discretizing them
B. Only Gradient boosting algorithm handles real valued attributes by discretizing them
C. Both algorithms can handle real valued attributes by discretizing them
D. None of these
12. Suppose you are using a bagging based algorithm say a Random Forest in model building.
Which of the following can be true?
1. Number of tree should be as large as possible.
2. You will have interpretability after using Random Forest
A. 1
B. 2
C. 1 and 2
D. None of these
13. Which of the following algorithm doesn’t uses learning Rate as of one of its
hyperparameter?
1. Gradient Boosting, 2. Extra Trees, 3. AdaBoost and 4. Random Forest.
Machine Learning
A. 1 and 3
B. 1 and 4
C. 2 and 3
D. 2 and 4
14. When you use the boosting algorithm you always consider the weak learners. Which of
the following is the main reason for having weak learners?
1. To prevent overfitting
2. To prevent under fitting
A. 1
B. 2
C. 1 and 2
D. None of these
15. Which of the following is true about the Gradient Boosting trees?
1. In each stage, introduce a new regression tree to compensate the shortcomings of
existing model
2. We can use gradient decent method for minimize the loss function
A. 1
B. 2
C. 1 and 2
D. None of these
6. D 7. C 8. B 9. C 10. A
Review Questions
1. Explain the architecture of Random Forest.
2. List the various types of Boosting.
3. Give thepython library functions used to implement ensemble learning?
4. Differenciate weak learner and strong learner.
5. How the final decision is taken in bagging and boosting methods?
Further Readings
MadanGopal, Applied Machine Learning, McGraw Hill Education, India, 2018.
S. N. Sivanandam, S.N. Deepa, Principles Of Soft Computing, Wiley Publications, Second
Edition, 2011.
Rajasekaran, S., Pai, G. A. Vijayalakshmi, Neural Networks, Fuzzy Logic and Genetic
Algorithm Synthesis And Applications, Prentice Hall of India, 2013.
Web Links
[Link]
algorithm
[Link]
ith_python_classification_algorithms_random_forest.htm
[Link]
[Link]
Objectives
After this unit, student would be able to
Understand basic concepts of seaborn
Learn basic difference between seaborn and matplotlib
Know how data visualization perform using seaborn
Introduction
One of the most popular methods for gaining a general understanding of the data's structure is
clustering. It can be summed up as the process of finding data subgroups where data points in the
same subgroup (cluster) are extremely similar and other data points in other clusters are very
dissimilar. To put it another way, we look for homogeneous subgroups within the data so that the
data points in each cluster are as comparable as feasible based on a similarity metric like the
Euclidean-based distance or the correlation-based distance. Choosing the similarity metric to
employ depends on the application.
Clustering analysis can be carried out either on the basis of samples or on the basis of
characteristics, where we attempt to identify subgroups of samples based on features. Here, we'll
talk about feature-based clustering. We utilize clustering in picture segmentation/compression to
group comparable regions together, market segmentation to discover clients that are similar to one
another in terms of behaviours or traits, document clustering based on subjects, etc.
Because we lack the ground truth to compare the output of the clustering algorithm to the true
labels in order to assess its effectiveness, clustering is regarded as an unsupervised learning method
in contrast to supervised learning. By dividing the data points into discrete subgroups, we simply
wish to try to study the data's structure.
Only Kmeans, one of the most popular clustering algorithms because of its simplicity, will be
covered in this chapter.
where wik=1 for data point xi if it belongs to cluster k; otherwise, wik=0. Also, μk is the centroid of
xi’s cluster.
It is a two-part minimization issue. First, we fix k and minimize J [Link]. Then we treat wik fixed
and minimize J w.r.t. Technically speaking, we update cluster assignments (E-step) after
differentiating J [Link]. After recalculating the centroids based on the cluster assignments from
the previous step (M-step), we distinguish J w.r.t. k. Consequently, E-step is:
To put it another way, choose the cluster to which the data point xi belongs based on its sum of
squared distances to the cluster's centroid.
And M-step is:
Which equates to recalculating each cluster's centroid to account for the new assignments.
Here are a few things to consider:
Since almost always the features in any dataset would have different units of measurements, such as
age vs income, it is advised to standardise the data to have a mean of zero and a standard deviation
of one. This is because clustering algorithms, including kmeans, use distance-based measurements to
determine the similarity between data points.
Different initializations may result in different clusters since the kmeans method may get trapped in
a local optimum and not converge to a global optimum due to its iterative nature and the random
initialization of centroids at the beginning of the algorithm. Therefore, it is advised to execute the
method with several centroids' initializations and select the results of the run that produced the
smallest sum of squared distance.
The same holds true for the assignment of examples as it does for the within-cluster variation:
Implementation
Here, we'll utilize a straightforward application of kmeans to just show a few ideas. The more
effective sklearn implementation will then take care of a lot of things for us.
import numpy as np
from [Link] import norm
class Kmeans:
'''Implementing Kmeans algorithm.'''
for k in range(self.n_clusters):
row_norm = norm(X - centroids[k, :], axis=1)
distance[:, k] = [Link](row_norm)
return distance
12.2 Applications
In many different applications, including market segmentation, document clustering, image
segmentation, and image compression, the kmeans technique is particularly well-liked and widely
employed. Usually, our aim when performing a cluster analysis is one of the following:
1. Obtain a meaningful understanding of the data's structure before proceeding.
2. If we think there is a large variance in the behaviors of distinct subgroups, we will cluster-
then-predict, where different models will be generated for different subgroups. Clustering
patients into several subgroups and developing a model for each subgroup to forecast the
likelihood of suffering a heart attack are two examples of that.
hierarchical clustering has an added advantage over k-means clustering in that its results can be
easily visualized using an attractive tree-based representation called a dendrogram.
Prerequisites
# Helper packages
library(dplyr) # for data manipulation
library(ggplot2) # for data visualization
# Modeling packages
library(cluster) # for general clustering algorithms
library(factoextra) # for visualizing cluster results
The Ames housing data will be used to explain the main ideas of hierarchical clustering. For the
sake of simplicity, we'll only utilize the 34 numeric features, but if you'd like to reproduce this
study using the entire set of features, please see our discussion in Section 20.7. We first standardise
the data because these features are measured at dramatically different magnitudes:
Agglomerative clustering, also known as AGNES (Agglomerative Nesting), operates from the
bottom up. In other words, each observation is first viewed as a leaf cluster with a single element.
The two clusters that are most similar to one another are joined into new, larger clusters (referred to
as nodes) at each stage of the process. This process is repeated until every single point is a part of
the same large cluster (root). The outcome is a tree that can be shown on a dendrogram.
when using maximum or complete linkage clustering. It usually results in more tightly packed
clusters.
Minimum or single linkage clustering: Calculates all pairwise differences between items in
clusters 1 and 2, then takes the difference with the least value as the linkage criterion. It
frequently results in lengthy, "loose" clusters.
Mean or average linkage clustering: The distance between the two clusters is calculated by
adding up all pairwise differences between the items in clusters 1 and 2, then taking the average
of those differences into account. The clusters it produces can differ in how compact they are.
Centroid linkage clustering:calculates the difference between the centroid for cluster 1 (a
mean vector with p elements, one for each variable), and the centroid for cluster 2.
whole by taking into account many viewpoints and making use of the advantages of several
models. This method not only improves accuracy but also offers resistance to data uncertainty.
Ensemble learning has proven to be a strong tool in many domains, providing more robust and
reliable forecasts by successfully combining predictions from numerous models.
5 4 5 4 4 4
Here, the goal variable for training data is y_train, and the independent variables in the training
data are called x_train. The independent variables x_test and the target variable y_test make up the
validation set.
Alternatively, you can use “VotingClassifier” module in sklearn as follows:
from [Link] import VotingClassifier
model1 = LogisticRegression(random_state=1)
model2 = [Link](random_state=1)
model = VotingClassifier(estimators=[('lr', model1), ('dt', model2)], voting='hard')
[Link](x_train,y_train)
[Link](x_test,y_test)
12.8 Averaging
Multiple forecasts are made for each data point when averaging, similar to the max voting method.
In this approach, the final prediction is made by averaging the results of all the models. When
computing probabilities for classification problems or making predictions in regression problems,
averaging can be applied.
For example, in the below case, the averaging method would take the average of all the values.i.e.
(5+4+5+4+4)/5 = 4.4
5 4 5 4 4 4.4
Sample Code
model1 = [Link]()
model2 = KNeighborsClassifier()
model3= LogisticRegression()
[Link](x_train,y_train)
[Link](x_train,y_train)
[Link](x_train,y_train)
pred1=model1.predict_proba(x_test)
pred2=model2.predict_proba(x_test)
pred3=model3.predict_proba(x_test)
finalpred=(pred1+pred2+pred3)/3
rating 5 4 5 4 4 4.41
Sample Code:
model1 = [Link]()
model2 = KNeighborsClassifier()
model3= LogisticRegression()
[Link](x_train,y_train)
[Link](x_train,y_train)
[Link](x_train,y_train)
pred1=model1.predict_proba(x_test)
pred2=model2.predict_proba(x_test)
pred3=model3.predict_proba(x_test)
finalpred=(pred1*0.3+pred2*0.3+pred3*0.4)
Summary
In summary, the end of chapter for the topics of k-means and hierarchical clustering involves
a comprehensive review of the key concepts techniques covered in the chapters. This includes
an understanding of how k-means is used for unsupervised, as well as the approaches for
hierarchical clustering such as dendrograms and agglomerative clustering.
k-Means algorithm a partitioning method that divides the dataset into k-overlapping clusters,
where each point belongs to only one cluster. The algorithm is iteratively until the optimal
centroid positions are found.
Hierarchical clustering, on the other hand, creates a hierarchy of clusters using either the
agglomer or divisive approach.
Agglomerative clustering, each data point starts as its own cluster, and then clusters are
merged until one cluster remains.
Divisive clustering begins with the whole data set as one cluster, which is recursively
subdivided into smaller clusters Both techniques have different applications and advantages,
and the choice of algorithm depends on the nature of the data and the problem at hand.
Clustering refers to the process of grouping similar objects or data points together based on
their similarities or differences. It is a technique in data mining and machine learning to
identify patterns in large datasets.
A dendrogram is a tree-like diagram that represents the hierarchy of clusters produced by
hierarchical clustering. It is a useful tool forizing the relationships between clusters and
identifying potential subgroups within the data.
K-Means Clustering is a popular unsupervised clustering algorithm that aims to partition
given dataset into k distinct,-overlapping clusters
K-means clustering algorithm is the most popular unsupervised learning technique utilized
for clustering analysis. It has been widely used across industries such as agriculture,
healthcare marketing, and more due to its simplicity and efficiency.
A dendrogram is a tree-like diagram that represents the hierarchy of clusters produced by
hierarchical clustering. It is a useful tool forizing the relationships between clusters and
identifying potential subgroups within the data. The calculation of Euclidean distance plays a
crucial role in data analysis, particularly in clustering and classification tasks. It is a
fundamental in distance-based algorithms such as-means and hierarchical clustering.
Keywords
k-Means Clustering is a popular partition-based algorithm that groups data points into 'k'
clusters by minimizing the sum of squared distances between data points and their cluster
centroids. It is widely used for tasks like customer segmentation and image compression.
The Average Method, also known as Mean Method, is a linkage criterion used in
Hierarchical Clustering. It calculates the distance between two clusters based on the average
distance of all data point pairs from each cluster, resulting in a balanced approach to cluster
merging.
Clustering with Weights is a technique that assigns varying importance to individual data
points during the clustering process. By incorporating weights, the algorithm considers
certain points more influential than others, leading to more nuanced and context-aware
clustering outcomes.
Comparative Analysis involves evaluating the performance, strengths, and weaknesses of
different clustering algorithms, such as k-Means, Hierarchical Clustering, DBSCAN, and
others. This analysis helps researchers and practitioners choose the most suitable method for
specific datasets and applications.
Clustering finds applications in diverse fields, including marketing, biology, finance, and
image analysis. For instance, in marketing, clustering aids in customer segmentation for
targeted marketing strategies, while in biology, it assists in classifying genes based on
expression patterns.
Hierarchical Clustering is a powerful unsupervised learning technique that groups data
into a tree-like hierarchy of clusters. It iteratively merges or divides clusters based on
proximity, creating a dendrogram that visually represents the cluster relationships.
Bagging, short for Bootstrap Aggregating, is an ensemble technique that builds multiple
models independently and combines their predictions through voting or averaging. By
training each model on bootstrapped subsets of the data, bagging reduces variance and
enhances model robustness, making it popular for improving decision tree-based models
like Random Forest.
Boosting is an ensemble approach that focuses on sequentially improving the performance
of weak learners by giving more weight to misclassified instances. Algorithms like AdaBoost
and Gradient Boosting Machines (GBM) are commonly used in boosting, creating a strong
learner from multiple weak learners and achieving high accuracy on challenging tasks.
Stacking, also known as Stacked Generalization, combines predictions from diverse base
models using a meta-model. It leverages the diverse strengths of individual models to make
more accurate predictions and can be applied to various machine learning tasks, enabling
effective model combination and performance enhancement.
Voting ensembles combine the predictions of multiple models by either majority voting or
weighted voting. This ensemble approach is simple yet effective, and it can be employed
with a variety of machine learning algorithms, including classifiers and regression models,
to produce more confident and reliable predictions.
Ensemble pruning and trimming involve reducing the size of an ensemble by removing
weak or redundant models. This process aims to improve efficiency, reduce memory
requirements, and prevent overfitting, ensuring that the ensemble maintains a good balance
between accuracy and complexity.
Evaluating ensemble models requires specific metrics like ensemble accuracy, area under the
ROC curve (AUC-ROC), or F1 score. Cross-validation and bootstrapping are employed to
assess ensemble performance and provide unbiased estimates of model effectiveness.
Ensemble learning in the context of deep learning involves combining multiple neural
networks or deep learning architectures to improve predictive performance and
generalization. Techniques like model averaging, stacking, and bagging can be applied to
neural networks, leveraging the power of ensembles in complex tasks and boosting overall
performance.
SelfAssessment
1. Which of the following is the primary objective of k-Means clustering?
A. Overfitting
B. Underfitting
C. Initial centroid sensitivity
D. Outliers
4. Which of the following methods is used to calculate the distance between two clusters in
Hierarchical Clustering?
A. Single Linkage
B. Average Linkage
C. Complete Linkage
D. All of the above
A. Bagging
B. Boosting
C. Stacking
D. Voting
A. K-Means
B. DBSCAN
11. In K-Means clustering, how are initial cluster centroids typically chosen?
12. Which ensemble clustering technique assigns data points to clusters based on majority
voting or averaging of cluster assignments from different clustering algorithms?
A. Bagging
B. Boosting
C. Stacking
D. Voting
13. In ensemble clustering, diversity among individual clustering algorithms is essential to:
14. Clustering evaluation metrics, such as Silhouette Score and Davies-Bouldin Index, are used
to assess:
A. Data classification
B. Data regression
C. Data visualization
D. Data clustering
6. B 7. B 8. C 9. D 10. A
Review Questions
1. Explain the k-Means algorithm in detail, including its steps and convergence criteria.
Discuss the impact of the initial centroids' selection on the clustering results.
2. Compare and contrast k-Means clustering and Hierarchical clustering in terms of their
working principles, advantages, and limitations. Provide real-world examples where each
algorithm would be suitable.
3. Illustrate the process of hierarchical clustering using a dendrogram. Explain how different
linkage methods (Single, Complete, and Average) influence the clustering results.
4. Discuss the concept of ensemble learning and its significance in improving predictive
performance. Explain two popular ensemble techniques and their applications in
clustering tasks.
5. Evaluate the effectiveness of ensemble pruning and trimming methods in reducing the
complexity of an ensemble while maintaining performance. Provide examples and discuss
the trade-offs in ensemble size reduction.
6. Explain how ensemble-based methods can address the limitations of k-Means clustering.
Provide a step-by-step guide on how to build an ensemble of k-Means models to improve
clustering accuracy and stability.
7. Discuss the role of diversity in ensemble learning and its impact on ensemble
performance. Describe three strategies to induce diversity among individual models
within an ensemble.
8. Compare the performance of k-Means clustering and hierarchical clustering on a given
dataset. Use appropriate evaluation metrics to measure the clustering quality, and analyze
the strengths and weaknesses of each algorithm's results.
9. Examine the challenges of using ensemble learning in deep learning models. Discuss how
ensembling can mitigate common issues like overfitting and improve the robustness of
deep learning predictions.
10. Analyze a real-world clustering problem and propose an ensemble-based solution.
Describe the choice of base clustering algorithms, the method of combining their results,
and the justification for using ensemble learning in this specific scenario.
Further Readings
MadanGopal, Applied Machine Learning, McGraw Hill Education, India, 2018.
S. N. Sivanandam, S.N. Deepa, Principles Of Soft Computing, Wiley Publications,
Second Edition, 2011.
Rajasekaran, S., Pai, G. A. Vijayalakshmi, Neural Networks, Fuzzy Logic and
Genetic Algorithm Synthesis And Applications, Prentice Hall of India, 2013.
N. P. Padhy, S. P. Simon, Soft Computing With Matlab Programming, Oxford
University Press, 2015.
Web Links
[Link]
clustering/
[Link]
evaluation-methods-and-drawbacks-aa03e644b48a
[Link]
ensemble-models/
Objectives
Understanding the processing of a neuron.
Understanding the Structure of Artificial Neural Networks.
Understanding the structure of a perceptron model and multilayer perceptron model.
Understanding the various evaluation metrics of ML models.
Understanding the basic concepts of deep neural networks.
Introduction
Artificial Neural Networks (ANNs) are relatively crude electronic models based on the neural
structure of the brain. The brain learns from experience and stores in the cells as in Figure 1.
Artificial neural networks try to mimic the functioning of brain.
Machine Learning
Even simple animal brains are capable of functions that are currently impossible for computers.
Computers do the things well, but they have trouble recognizing even simple patterns. This unit
explores the technical aspects and makes you to understand the processing of neuron too along
with ANN Architecture.
Dendrite
Each neuron has fine, hair like tubular structures (extensions) around it. They branch out into tree
around the cell body. They accept incoming signals.
Axon
It is a long, thin, tubular structure which works like a transmission line. Synapse: Neurons are
connected to one another in complex spatial arrangement. When axon reaches its final destination it
branches again called as terminal arborization. At the end of axon are highly complex and
specialized structures called synapses. Connection between two neurons takes place at these
synapses.
Dendrites receive the input through the synapses of other neurons. The soma processes these
incoming signals over time and converts that processed value into an output, which is sent out to
other neurons through the axon and the synapses.
Machine Learning
13.3 Perceptron
Perceptron was developed in 1958 by Frank Rosenblatt,a researcher in neuro-physiology to perform
a kind of pattern recognition tasks. It resulted from the solution of classification [Link] shown
in figure 6, the perceptron model takes a vector of real-valued inputs, calculates a linear
combination of these inputs, then outputs +1 if the result is greater than the threshold and -1 if the
result is not greater than the [Link] was developed as simplest yet powerful classifier
providing the linear separability of class patterns or examples. Perceptron can’t handle tasks, which
are not linearly separable. We can say that, A set of points in 2-dimensional space is linearly
separable if this sets of points can be separated by a straight line. The perceptron criterion function
is based on misclassification error, which means the number of samples misclassified. The
perceptron architecture is as given below.
only processing unit where the threshold activation function is used and gives the final output as
+1 or -1.
The history has proved that the neural networks can overcome the limitations of Rosenblatt’s
perceptron. The neural networks primarily solve the regression problems based on minimum
squared error criterion. This employed the gradient procedures for minimization. The perceptron
was superseded by more sophisticated and powerful neuron and neural network structures. A
popular network used today is the multilayer network, which is discussed in the next section.
Binary-Class Classification
The Figure 4 is describing the concept of binary class model. The output layer is having only one
neuron illustrating the yes / no response. Output = 1 means Yes and the output = 0 means No.
Hence, this model is known as binary-class classification.
Any data, which can be classified into two categories, is also known as binary-class classification as
shown in Figure 8.
Machine Learning
When it is interpreted as a vector in weight space, the gradient specifies the direction that produces
the steepest increase in E, the derivative. The negative of this vector, therefore, gives the direction
of steepest decrease. Here, eta is a positive constant (should be less than 1), called as the learning
rate, which determines the step size in the gradient descent search.
Backpropagation Algorithm
MLP networks trained by the Backpropagation algorithm are capable of expressing a rich variety of
nonlinear decision surfaces or approximating nonlinear functions. This also uses the gradient
descent [Link] Backpropagation algorithm learns the weights for an MLP network, given a
network with a fixed set of units and interconnections. It employs gradient descent to attempt to
minimize the squared error between the network outputs and the target values for these outputs.
A typical feed-forward neural network is made up of a hierarchy of layers, and the neurons in the
network are arranged along these layers as discussed in the previous section. The external
environment is connected to the network through input layer and the output layer. The multi-layer
perceptron network is a feed-forward neural network with one or more hidden layers. Each hidden
layer has its own specific function. The working style of Backpropagation algorithm is divided into
two parts. First is in forward direction and the second is in backward direction as shown in Figure
11 and figure 12.
Machine Learning
modeling. The learning portion of creating models spawned the development of artificial neural
networks.
Summary
This unit explored the basic concepts of Artificial Neural Networks, stating from what is biological
neuron. Understood that the imitation of biological neuron became artificial neuron. The processing
of a artificial neuron was explained clearly using a diagram. The Structure of Artificial Neural
Networks was discussed in [Link] the difference between Biological Neuron and
Artificial [Link] of Activation Functions and different types of activation function was
explained in this [Link] addition to this, the structure of perceptron model and multilayer
perceptron model or feed-forward neural network was discussed along with back-propagation. An
introduction to deep networks is also highlighted in this unit.
Keywords
Biological Neuron
Artificial Neuron
Artificial Neural Networks
Activation Function
Binary classification
Multi-class classification
Perceptron
Backpropagation
Deep neural networks
Self Assessment
1. How many hidden layers can be present in a multi layer neural network?
A. 0
B. 1
C. 2
D. ‘N’
Machine Learning
C. Multi-class Classification
D. All the above
A. Yes
B. No
14. Tangent Hyperbolic Activation function values ranging from _______ to _______.
A. 0 to 1
B. -1 to +1
C. -1 to 0
D. None of the above
15. Artificial Neural Network architecture is optimized using ___________ after completing
the training of the model.
A. Training Dataset
B. Testing Dataset
C. Validation Dataset
D. Computer vision
6. D 7. D 8. B 9. A 10. C
Review Questions
1. Explain the architecture of Artificial Neural Networks.
2. List the various tools used to implement ANN.
3. What are all the activation functions used for training ANN?
4. Givean example how the weights are adjusted.
5. Differentiate biological neuron and artificial neuron.
Further readings
Madan Gopal, Applied Machine Learning, McGraw Hill Education, India, 2018.
S. N. Sivanandam, S.N. Deepa, Principles Of Soft Computing, Wiley Publications,
Second Edition, 2011.
Rajasekaran, S., Pai, G. A. Vijayalakshmi, Neural Networks, Fuzzy Logic and Genetic
Algorithm Synthesis And Applications, Prentice Hall of India, 2013.
N. P. Padhy, S. P. Simon, Soft Computing With Matlab Programming, Oxford
University Press, 2015.
Web Links
[Link]
[Link]
neural-network/
[Link]
[Link]
Objectives
• understand basic of network security.
• understand network security issues
• learn security goals
• understand security services
• approaches of network security
Introduction
Basic and advanced ideas of ANNs are provided via the Artificial Neural Network Tutorial. Our
Artificial Neural Network tutorial was created for both professionals and beginners.
The phrase "artificial neural network" refers to a branch of artificial intelligence that was inspired
by biology and is based on the brain. A computational network based on biological neural
networks, which create the structure of the human brain, is typically referred to as an artificial
neural network. Artificial neural networks also feature neurons that are linked to each other in
different layers of the networks, just as neurons in a real brain. Nodes are the name for these
neurons.
The given figure illustrates the typical diagram of Biological Neural Network.
The typical Artificial Neural Network looks something like the given figure.
In artificial neural networks, dendrites from biological neural networks serve as inputs, cell nuclei
serve as nodes, synapses serve as weights, and axons serve as outputs.
Dendrites Inputs
Synapse Weights
Axon Output
Artificial neural networks are used in artificial intelligence to simulate the network of neurons that
make up the human brain, giving computers the ability to comprehend information and make
decisions in a manner similar to that of a person. Computers are programmed to behave exactly
like interconnected brain cells to create an artificial neural network.
The human brain contains about 1000 billion neurons. Between 1,000 to 100,000 association points
are present in each neuron. Data is distributedly stored in the human brain, allowing us to
simultaneously access many pieces of information from memory as needed. The human brain is
said to contain a staggering number of incredible parallel processors.
Consider an example of a digital logic gate that accepts input and outputs so that we may better
grasp the artificial neural network. Two inputs are required for the "OR" gate. If either one or both
of the inputs are "On," the output will also be "On". If both inputs are "Off," the output will also be
"Off." In this case, output is dependent on input. Our brains do not carry out the same function.
Because our brain's neurons are constantly "learning," the relationship between outputs and inputs
is constantly changing.
Input Layer
As the name implies, it accepts inputs in a variety of programming-provided formats.
Hidden Layers
The hidden layer presents in-between input and output layers. It performs all the calculations to
find hidden features and patterns.
Output Layers
The hidden layer is used to transform the input into a variety of outputs, which are then
communicated through this layer.
When given input, the artificial neural network computes the weighted total of the inputs and
incorporates a bias. A transfer function is used to visualise this computation.
In order to produce the output, it passes the weighted total as an input to an activation function. A
node's activation functions determine whether or not it should fire. The output layer is only
accessible to individuals who are fired. Depending on the type of task we are completing, there are
many activation functions that can be used.
Following ANN training, the data may still produce output even with insufficient data. The
relevance of the missing data in this situation is what causes the performance loss.
a fault-tolerant attitude
The network is fault-tolerant since expropriation of one or more ANN cells does not prevent the
network from producing output.
Unrecognized networkbehavior:
It is the most important ANN issue. When an ANN generates a testing solution, it doesn't explain
why or how. It erodes network confidence.
Hardware reliance
According to their structure, artificial neural networks require processors with parallel processing
power. As a result, the equipment's realization is dependent.
Having trouble getting the network to see the problem:
ANNs can process data that is numerical. Before using ANN, problems must be transformed into
numerical values. The network's performance will be directly impacted by the presentation
mechanism that must be decided here. It is dependent on the user's skills.
Each input is then multiplied by the weights that correspond to it (these weights are the
information that the artificial neural networks use to solve a particular problem). In the artificial
neural network, these weights often indicate how well neurons are connected to one another. Inside
the computer unit, a summary of each weighted input is created.
The output is made non-zero by adding bias if the weighted total is equal to zero, or else something
else is added to scale up the output to the system's reaction. The input for bias is the same, and the
weight is 1. The sum of the weighted inputs in this case can range from 0 to positive infinity. Here,
a certain maximum value is benchmarked to maintain the response within the bounds of the
intended value, and the sum of the weighted inputs is fed through the activation function.
The set of transfer functions utilised to produce the desired output is referred to as the activation
function. A variety of activation functions exist, although they are mainly either linear or non-linear
sets of functions. The Binary, linear, and Tan hyperbolic sigmoidal activation function sets are a few
of the often employed sets of activation functions. Let's examine each of these in more detail:
Binary
The output of a binary activation function is either a one or a zero. Here, a threshold value has been
established in order to achieve this. The final output of the activation function is returned as one or
0 depending on whether the net weighted input of neurons is greater than 1.
Sigmoidal Hyperbolic:
The Sigmoidal Hyperbola function is generally seen as an "S" shaped curve. Here the tan
hyperbolic function is used to approximate output from the actual net input. The function is
defined as:
Feedback ANN
The output of a feedback ANN is fed back into the network to achieve the best internally evolved
results. based on the Centre for Atmospheric Research at the University of Massachusetts, Lowell.
The feedback networks are excellent for addressing optimization problems since they feed
information back into themselves. Utilizing feedback ANNs, the internal system error repairs.
Feed-Forward ANN
A feed-forward network is a type of neural network that consists of at least one layer of neurons as
well as input and output layers. The network's intensity can be observed based on the collective
behavior of the connected neurons, and the output is chosen by evaluating the network's output in
the context of its input. The main benefit of this network is that it learns to assess and identify input
patterns.
Logistic Regression
Random Forest
Support Vector Machine (SVM)
We'll use the scikit-learn library in Python for implementing these models and evaluating their
performance. Additionally, we'll use three different datasets to showcase their performance across
diverse scenarios. Let's proceed with the implementation.
X3 = dataset_3.data
y3 = dataset_3.target
X_train_3, X_test_3, y_train_3, y_test_3 = train_test_split(X3, y3, test_size=0.2, random_state=42)
# Implement SVM
svm_model = SVC()
svm_model.fit(X_train_3, y_train_3)
# Evaluate SVM
svm_predictions = svm_model.predict(X_test_3)
svm_accuracy = accuracy_score(y_test_3, svm_predictions)
print("Support Vector Machine Accuracy:", svm_accuracy)
By executing the code, you will obtain the accuracy scores for each model on their respective
datasets. This allows for a performance comparison between the three models. Keep in mind that
accuracy alone may not provide a comprehensive evaluation, and it's advisable to consider
additional metrics based on the specific requirements and characteristics of your datasets.
Summary
The phrase "artificial neural network" refers to a branch of artificial intelligence that was
inspired by biology and is based on the brain. A computational network based on biological
neural networks, which create the structure of the human brain, is typically referred to as an
artificial neural network.
The biological neural networks that shape the structure of the human brain are where the
phrase "artificial neural network" originates
The components of a neural network is necessary to comprehend the idea of the architecture
of an artificial neural network. A vast number of artificial neurons, also known as units, are
placed in a hierarchy of layers to form what is known as a neural network.
The hidden layer presents in-between input and output layers. It performs all the calculations
to find hidden features and patterns.
Artificial neural networks have a numerical value that allows them to carry out multiple tasks
at once.
Traditional programming does not employ a database; instead, it stores data on the entire
network. The network continues to function even if some data disappears from one location
temporarily.
The structures and operations of human neurons serve as the basis for artificial neural
networks. It is also known as neural networks or neural nets.
Synapses are the connections that allow impulses to be sent from dendrites to the cell body of
biological neurons. In artificial neurons, synapse weights connect the one-layer nodes to the
next-layer nodes.
Learning takes place in the cell body nucleus or soma of biological neurons, which possesses a
nucleus that aids in impulse processing. If the impulses are strong enough to pass the
threshold, an action potential is created and moves through the axons.
The pace at which a biological neuron fires when an impulse is potent enough to cross the
threshold is known as activation.
Keywords
Artificial Neural Networks: Computational models inspired by the structure and
functioning of the human brain, used in machine learning for solving complex problems by
simulating interconnected artificial neurons.
Perceptron: The fundamental building block of an artificial neural network, comprising a
weighted input sum, an activation function, and an output. It processes input data and
produces a binary output based on the weighted sum.
Activation Function: A mathematical function applied to the output of a perceptron or a
neuron in a neural network. It introduces non-linearity, allowing the network to model
complex relationships and make predictions based on the input.
Feedforward Neural Networks: Neural networks composed of interconnected layers of
perceptrons or neurons, where information flows only in one direction, from the input layer
through hidden layers to the output layer. They are used for tasks such as classification and
regression.
Backpropagation: An algorithm used to train neural networks by adjusting the weights
based on the calculated errors between the predicted outputs and the desired outputs. It uses
gradient descent to iteratively minimize the error and improve the network's performance.
Gradient Descent: An optimization algorithm used in backpropagation to update the
weights of a neural network. It calculates the gradient of the error function with respect to the
weights and adjusts the weights in the direction of steepest descent to minimize the error.
Multilayer Perceptron: A type of feedforward neural network with multiple hidden layers
between the input and output layers. It is a versatile architecture capable of learning complex
relationships and widely used for various tasks.
Convolutional Neural Networks: Neural networks specifically designed for processing
grid-like data, such as images. They utilize convolutional layers to extract features
hierarchically and are effective in tasks like image classification and object detection.
Recurrent Neural Networks: Neural networks designed for processing sequential data with
temporal dependencies. They have feedback connections that enable them to store and utilize
information from previous time steps, making them suitable for tasks like natural language
processing and time series analysis.
Image Classification: The task of assigning labels or categories to images based on their
content. Artificial neural networks, particularly convolutional neural networks, have shown
remarkable performance in image classification tasks.
Object Detection: The process of identifying and locating objects within images or videos.
Convolutional neural networks are widely used in object detection algorithms to accurately
detect and classify objects.
Natural Language Processing: A field of study focused on enabling computers to
understand, interpret, and generate human language. Artificial neural networks, including
recurrent neural networks, are used in tasks such as language translation, sentiment analysis,
and text generation.
Time Series Analysis: The analysis of data points collected over time to identify patterns,
trends, and make predictions. Recurrent neural networks are effective in time series analysis
as they can model temporal dependencies and capture long-term patterns.
Recommendation Systems: Systems that provide personalized recommendations to users
based on their preferences and behaviors. Neural networks, particularly collaborative filtering
techniques, are commonly used to build recommendation systems and improve the accuracy
of recommendations.
Hyperparameter Tuning: The process of selecting the optimal values for the
hyperparameters of a neural network. It involves techniques such as grid search and random
search to find the hyperparameter configuration that maximizes the model's performance.
Regularization Techniques: Techniques used to prevent overfitting in neural networks by
introducing additional constraints or penalties on the model's parameters. Common
regularization techniques include L1 and L2 regularization, dropout, and early stopping.
Model Evaluation: The process of assessing the performance of a trained neural network. It
involves using various metrics such as accuracy, precision, recall, and F1 score to measure
how well the model predicts the desired outputs.
Accuracy: A metric used to measure the performance of a classification model, representing
the ratio of correctly predicted instances to the total number of instances in the dataset.
Precision: A metric that measures the proportion of true positive predictions out of all
positive predictions made by the model. It is used to evaluate the correctness of positive
predictions.
Recall: A metric that measures the proportion of true positive predictions out of all actual
positive instances in the dataset. It is used to evaluate the model's ability to find all positive
instances.
F1 Score: A metric that combines precision and recall into a single value, providing a
balanced measure of a model's performance. It is the harmonic mean of precision and recall,
and it is useful when the class distribution is imbalanced.
SelfAssessment
1. Why are biological neural networks necessary?
A. To tackle problems involving machine vision and natural language
B. processing, as well as to use heuristic search techniques to locate solutions.
C. to create a clever, user-friendly, interactive human system.
D. all the aforementioned
B. to be task-specific,
C. to bring the computer closer to the user,
D. and to be versatile.
8. Describe categorization.
A. Choosing the features to include in a pattern recognition challenge.
B. establishing the class to which an input pattern belongs.
C. selecting the neural network type to be used
D. None of the previously listed
15. The weights and biases in an ANN are learned during the process of:
A. Forward propagation
B. Backpropagation
C. Gradient descent
D. Feature engineering
6. B 7. A 8. B 9. C 10. C
Review Questions
1. Explain the concept of a perceptron and how it functions within an artificial neural network.
2. Discuss the importance of activation functions in artificial neural networks. Provide examples
of commonly used activation functions and their characteristics.
3. Describe the backpropagation algorithm and its role in training artificial neural networks.
Explain how gradient descent is utilized in backpropagation.
4. Compare and contrast feedforward neural networks and recurrent neural networks. Discuss
the advantages and applications of each type.
5. Explain the architecture and working principles of convolutional neural networks (CNNs).
Discuss their significance in image processing tasks such as image classification and object
detection.
6. Describe the concept of regularization in neural networks. Discuss common regularization
techniques used to prevent overfitting and improve model generalization.
7. Discuss the importance of hyperparameter tuning in neural networks. Explain different
methods and strategies for finding optimal hyperparameter configurations.
8. Explain the concept of model evaluation in artificial neural networks. Discuss commonly used
evaluation metrics and their significance in assessing model performance.
9. Discuss the challenges and limitations of artificial neural networks. Highlight specific areas
where neural networks may face difficulties or exhibit limitations.
10. Describe the applications of artificial neural networks in real-world scenarios, such as natural
language processing, time series analysis, or recommendation systems. Provide examples and
discuss their effectiveness in these applications.
Further Readings
Madan Gopal, Applied Machine Learning, McGraw Hill Education, India, 2018.
S. N. Sivanandam, S.N. Deepa, Principles Of Soft Computing, Wiley Publications,
Second Edition, 2011.
Rajasekaran, S., Pai, G. A. Vijayalakshmi, Neural Networks, Fuzzy Logic and Genetic
Algorithm Synthesis And Applications, Prentice Hall of India, 2013.
N. P. Padhy, S. P. Simon, Soft Computing With Matlab Programming, Oxford
University Press, 2015.
Web Links
[Link]
[Link]
neural-network/
[Link]
[Link]