Understanding Machine Learning Basics
Understanding Machine Learning Basics
Activity 1: Autodraw - Experience the power of machine learning with Autodraw! Autodraw
combines machine learning with the creativity of talented artists, allowing you to draw
things quickly and effortlessly.
99
TYPES OF MACHINE LEARNING
In Chapter 1, we introduced you to the fascinating world of artificial intelligence (AI)
and its various learning mechanisms. We discussed three main types of machine learning:
Supervised Learning, Unsupervised Learning, and Reinforcement Learning. These terms
represent the algorithms that drive AI systems, serving as the building blocks for
programming intelligent behavior and decision-making processes. Now, let us delve deeper
into how these algorithms shape the landscape of AI applications.
● Supervised learning involves the model learning from labeled data, where the input
data is accompanied by the correct output. The algorithm learns to map input data
to output labels based on example input-output pairs provided during training. The
goal is to learn a mapping function so that the model can make predictions on unseen
data. Examples include linear regression, logistic regression, decision trees, support
vector machines, and neural networks.
● Unsupervised learning, on the other hand, deals with unlabelled data, where the
algorithm tries to find hidden patterns or structure without explicit guidance. The
goal of this is to explore and discover inherent structures or relationships within the
data, such as clusters or associations. Examples include k-means clustering,
hierarchical clustering, principal component analysis, and autoencoders.
● Finally, reinforcement learning involves an agent learning to make decisions by
interacting with an environment to maximize cumulative rewards. Through trial and
error, the agent learns a policy or strategy to take actions that lead to the highest
cumulative reward over time. These rewards serve as feedback, guiding the agent
towards favorable actions, while penalties discourage undesirable behavior. This
iterative learning approach is particularly effective in scenarios requiring a sequence
of decisions, such as game-playing or robot control, where the agent adapts its
behavior based on past experiences and outcomes. Examples include Q-learning,
deep Q-networks, policy gradients, and actor-critic methods.
100
A. SUPERVISED LEARNING
Supervised learning stands out as one of the foundational types of Machine Learning.
It is a powerful approach that allows machines to learn from labeled data, making
predictions or decisions based on that learning. Within supervised learning, two primary
types of algorithms emerge:
1. Regression – works with continuous data
2. Classification – works with discrete data
1. REGRESSION
Understanding Correlation: The Foundation of Regression Analysis
In data analysis, correlation is a fundamental concept that helps us grasp the
relationship between variables, laying the groundwork for predictive modeling and insightful
analysis. Correlation is a measure of the strength of a linear relationship between two
quantitative variables (e.g. price, sales). If the change in one variable appears to be
accompanied by a change in the other variable the two variables are said to be correlated
and this inter dependence is called correlation.
Types of Correlation:
101
Causation
Causation indicates that one event is the result of the occurrence of the other event.
Example: Since there is hot weather, the person will use more sunscreen or eat more ice
cream.
Sometimes, these two events may be correlated also. Example: smoking causes an increase
in the risk of developing lung cancer or it can correlate with another like-smoking is
correlated with alcoholism, but it does not cause alcoholism. Therefore, we can say
causation is not always correlation.
PEARSON’S R
Pearson's correlation coefficient (often denoted as Pearson's r) is one of the crucial
factors to consider when assessing the appropriateness of regression analysis. Pearson's r
measures the strength and direction of the linear relationship between two continuous
variables. In the context of regression analysis, a high degree of correlation between the
independent and dependent variables suggests that there may be a meaningful relationship
to explore using regression techniques.
The requirements when considering the use of Pearson's correlation coefficient are:
1. Scale of measurement should be interval or ratio.
2. Variables should be approximately normally distributed.
3. The association should be linear.
4. There should be no outliers in the data.
Pearson’s r is calculated using the formula:
102
Solution:
For the Calculation of the Pearson Correlation Coefficient, we will first calculate the
following values:
It is important to note that, regression analysis may not be suitable in certain situations:
1. No Correlation: If there is no correlation between the variables, meaning they change
independently of each other, regression analysis will not provide meaningful insights
or predictions.
2. Non-linear Relationships: While regression can model linear relationships well, it
may not capture more complex, non-linear relationships effectively. In such cases,
alternative techniques like polynomial regression or non-linear regression may be
more appropriate.
103
3. Outliers: Outliers, or extreme data points, can disproportionately influence the
regression model and lead to inaccurate predictions. In the presence of outliers, it is
essential to assess their impact and consider alternative modeling approaches.
4. Violation of Assumptions: Regression analysis relies on certain assumptions, such as
the linearity of relationships and the absence of multicollinearity (high correlation
between predictor variables). If these assumptions are violated, the results of the
regression analysis may be unreliable.
REGRESSION
Regression is a statistical technique used to model the relationship between a
dependent variable and one or more independent variables. Its primary objective is to
understand and predict the value of the dependent variable based on the values of the
independent variables. In simpler terms, regression helps us understand how changes in
one or more variables are associated with changes in another variable.
Regression analysis is particularly useful when dealing with continuous data, where
variables can take on any value within a certain range. For example, variables such as height,
temperature, salary, and time are all continuous, meaning they can be measured along a
continuous scale. In regression, these continuous variables are used to predict or explain
the variability in another continuous variable, known as the dependent variable. By
analyzing the relationship between the independent and dependent variables, regression
allows us to make predictions and understand how changes in one variable may impact the
other. This makes regression a powerful tool for forecasting, prediction, and understanding
complex relationships in various fields such as economics, social sciences, and healthcare.
When we make a distribution in which there is an involvement of more than one
variable, then such an analysis is called Regression Analysis. It generally focuses on
finding or rather predicting the value of the variable that is dependent on the other.
Let there be two variables x and y. If y depends on x, then the result comes in the form of a
simple regression. Furthermore, we name the variables x and y as:
y – Regression / Dependent / Explained Variable.
It is the variable we want to predict or understand.
104
FINDING THE LINE
Regression analysis relies on the concept of the regression line or curve, which
represents the best-fit relationship between the variables involved. This line or curve is
determined by minimizing the differences between the observed values of the dependent
variable and the values predicted by the regression model.
The least squares method is commonly employed to find this best-fit line or curve.
This method minimizes the squared differences between observed and predicted values,
ensuring that the regression line captures the overall trend or pattern in the data as
accurately as possible. By systematically estimating the parameters of the regression
model, such as the intercept and slope, the least squares method provides a precise
description of the relationship between the variables.
Through the least squares method, regression analysis yields estimate of the
regression coefficients that define the best-fit relationship between the variables. These
coefficients allow for making predictions about the dependent variable based on the values
of the independent variable(s) with greater accuracy and reliability. As a result, this is widely
used in regression analysis.
Properties of the Regression line:
● The line minimizes the sum of squared
difference between the observed values
(actual y-value) and the predicted value (ŷ
value)
● The line passes through the mean of
independent and dependent features.
Example 1
In the example of 6 people with different ages and different weight, let us draw the line of
best fit in Excel.
Solution:
Step 1: Select the Age and Weight.
Step 2: Insert a scatter chart and make changes to the following:
Trendline Name: Linear, check Display Equation on Chart
X axis minimum : 20
105
Step 3: Let us verify the values of slope and intercept using slope() and intercept() function
in excel.
Step 4: Click on any cell and type =slope( Now, select the values of Weight, and then type
comma. Now, select the values of Age and press enter.
Step 5: Click on any cell and type =intercept( Now, select the values of Weight, and then
type comma. Now, select the values of Age and press enter.
106
Advantages of Linear regression
● Simple technique and easy to implement
● Efficient to train the machine on this model
Disadvantages of Linear regression
1. Sensitivity to outliers, which can significantly impact the analysis.
2. Limited to linear relationships between variables.
[Link]
import numpy as np
import [Link] as plt
# Sample data
x = [Link]([1, 2, 3, 4, 5])
y = [Link]([2, 4, 5, 4, 5])
# Calculate mean and standard deviation
x_mean = [Link](x)
y_mean = [Link](y)
x_std = [Link](x)
y_std = [Link](y)
# Calculate covariance and slope
covariance = [Link]((x - x_mean) * (y - y_mean)) / (len(x) - 1)
slope = covariance / (x_std**2)
# Calculate y-intercept (b)
intercept = y_mean - slope * x_mean
# Predicted values
y_pred = slope * x + intercept
# Plot data and regression line
[Link](x, y)
[Link](x, y_pred, color='red')
# Add labels and title
[Link]('x')
[Link]('y')
[Link]('Simple Linear Regression')
# Show the plot
[Link]()
# Print slope and intercept
print(f"Slope: {slope:.2f}")
print(f"Intercept: {intercept:.2f}")
107
This program:
REFERENCES
Video links:
● [Link]
● [Link]
● [Link]
● [Link]
2. CLASSIFICATION
For example, let us say, you live in a gated housing society and your society has
separate dustbins for different types of waste: paper waste, plastic waste, food waste and so
on. What you are basically doing over here is classifying the waste into different categories
and then labeling each category. In the picture given below, we are assigning the labels
‘paper’, ‘metal’, ‘plastic’, and so on to different types of waste.
108
Look at the two graphs below and suggest which graph represents the classification
problem.
Graph 1 Graph 2
____________________________________ ____________________________________
109
● Classification Model: An algorithm or technique is used to build the classification
model. This model learns from the training data to predict the class labels of new,
unseen data instances. It aims to generalize from the patterns and relationships in
the training data to make accurate predictions.
● Prediction or Inference: Once trained, the classification model is used to predict the
class labels of new data instances. This process, known as prediction or inference,
relies on the learned patterns and relationships from the training data..
Types of classification
The four main types of classification are:
1) Binary Classification
2) Multi-Class Classification
3) Multi-Label Classification
4) Imbalanced Classification
Classification Binary Multi-Class Multi-Label Imbalanced
Type Classification Classification Classification Classification
Classification Classification tasks
Classification tasks where each with unequally
Classification
tasks with more example may distributed class
Description tasks with two
than two class belong to labels, typically with
class labels.
labels. multiple class a majority and
labels. minority class.
• Email spam
• Face
detection -
classification
spam or not
• Plant species • Photo
• Conversion
classification classification
prediction -
• Optical - objects • Fraud detection
buy or not
character present in • Outlier detection
Example • Medical test
recognition the photo • Medical
- Cancer
• Image (bicycle, diagnostic tests
detected or
classification apple,
not
into person, etc.)
• Exam
thousands of
results -
classes
pass/fail
110
Why KNN Algorithm is Needed:
KNN is particularly useful when dealing with classification problems where the
decision boundaries are not clearly defined or when the dataset does not have a well-
defined structure. It provides a simple yet effective method for identifying the category or
class of a new data point based on its similarity to existing data points.
111
For advanced learners – Python Program for K Nearest Neighbor Algorithm
# importing libraries
import numpy as nm
import [Link] as mtp
import pandas as pd
#importing datasets
data_set= pd.read_csv('user_data.csv')
#feature Scaling
from [Link] import StandardScaler
st_x= StandardScaler()
x_train= st_x.fit_transform(x_train)
x_test= st_x.transform(x_test)
Reference: [Link]
learning
Note to the teacher: Can introduce Teachable Machine to develop any image classifier
problem.
Website: [Link]
REFERENCES
Video Session:
Classification: [Link]
KNN Algorithm: [Link]
112
B. UNSUPERVISED LEARNING
3. CLUSTERING
Clustering, or cluster analysis, is a machine learning technique used to group unlabeled
dataset into clusters or groups based on similarity. Clustering aims to organize data points
into groups where points within the same group are more similar to each other than to those
in other groups. It involves finding patterns or structures in the data without the need for
predefined class labels. It does it by finding some similar patterns in the unlabelled dataset
such as shape, size, color, behavior, etc., and divides them as per the presence and absence
of those similar patterns. It is an unsupervised learning method, hence no supervision is
provided to the algorithm, and it deals with the unlabeled dataset.
The clustering technique is commonly used for statistical data analysis.
Example: Let us consider the clustering technique using a real-world example. Imagine you
are visiting a shopping center where items are grouped together based on their similarities.
For instance, in the fruits section, you will find apples, bananas, and grapes neatly arranged
together. This organization makes it convenient for shoppers to locate specific items they
are looking for.
Based on colour
Based on size
In a similar way, clustering algorithms group similar data points together based on common
characteristics or features. This approach helps in organizing and making sense of large
datasets in various tasks, such as market segmentation, image recognition, and customer
segmentation.
113
How Clustering Works:
To cluster data effectively, follow these key steps:
1) Prepare the Data: Select the right features for clustering and make sure the data is
ready by scaling or transforming it as needed.
2) Create Similarity Metrics: Define how similar data points are by comparing their
features. This similarity measure is crucial for clustering.
3) Run the Clustering Algorithm: Apply a clustering algorithm to group the data. Choose
one that works well with your dataset size and characteristics.
4) Interpret the Results: Analyze the clusters to understand what they represent. Since
clustering is unsupervised, interpretation is essential for assessing the quality of the
clusters.
Types of Clustering Methods
Some of the common clustering methods used in Machine learning are:
1) Partitioning Clustering
2) Density-Based Clustering
3) Distribution Model-Based Clustering
4) Hierarchical Clustering
1. Partitioning Clustering
It is a type of clustering that divides the data into non-
hierarchical groups. It is also known as the centroid-
based method. The most common example of
partitioning clustering is the K-Means Clustering
algorithm. In this type, the dataset is divided into a
set of k groups, where k is used to define the number
of pre-defined groups. The cluster center is created
in such a way that the distance between the data
points of one cluster is minimum as compared to
another cluster centroid.
2. Density-Based Clustering
The density-based clustering method connects the
highly-dense areas into clusters, and the arbitrarily
shaped distributions are formed as long as the dense
region can be connected. This algorithm does it by
identifying different clusters in the dataset and
connects the areas of high densities into clusters.
The dense areas in data space are divided from each
other by sparser areas. These algorithms can face
difficulty in clustering the data points if the dataset
has varying densities and high dimensions.
114
3. Distribution Model-Based Clustering
In the distribution model-based clustering method,
the data is divided based on the probability of how a
dataset belongs to a particular distribution. The
grouping is done by assuming some distributions
commonly Gaussian Distribution.
The example of this type is the Expectation-
Maximization Clustering algorithm that uses
Gaussian Mixture Models (GMM).
4. Hierarchical Clustering
Hierarchical clustering can be used as an alternative
for the partitioned clustering as there is no
requirement of pre-specifying the number of clusters
to be created. In this technique, the dataset is
divided into clusters to create a tree-like structure,
which is also called a dendrogram. The observations
or any number of clusters can be selected by cutting
the tree at the correct level. The most common
example of this method is the Agglomerative
Hierarchical algorithm.
K- Means clustering
K-Means Clustering is an unsupervised learning algorithm that is used to solve the
clustering problems in machine learning or data science. The k-means algorithm is one of
the most popular clustering algorithms. It classifies the dataset by dividing the samples into
different clusters of equal variances. The number of clusters must be specified in this
algorithm.
115
Activity: Visual AI: This tool allows you to visualize K-means clustering in real-time. Upload
your own data or use provided examples, adjust parameters, and see how clusters change
visually using the link Visualise k-means
116
[Link](centers[:, 0], centers[:, 1], c='red', s=200, alpha=0.75)
[Link]('K-means Clustering')
[Link]('Feature 1')
[Link]('Feature 2')
[Link]()
Output
REFERENCES
Video Session
Videos: Clustering: [Link]
K-means clustering: [Link]
EXERCISES
[Link] Choice Questions
1. Which of the following are the types of correlation?
a. Positive correlation
b. Negative Correlation
c. No correlation
d. All of the above
2. Which of the following techniques is an analysis of the relationship between
two variables to provide the prediction mechanism?
a. Standard error
b. Correlation
c. Regression
d. None of the above
117