R Programming Temperature Conversion Guide
R Programming Temperature Conversion Guide
1. Program to convert the given temperature from Fahrenheit to Celsius and vice versa depending upon user’s
choice.
Output:
25 degrees Celsius is equal to 298.15 Kelvin
Output:
25 degrees Celsius is equal to 77 Fahrenheit
Output:
77 degrees Fahrenheit is equal to 25 Celsius
Output:
298.15 Kelvin is equal to 25 degrees Celsius
Output:
77 degrees Fahrenheit is equal to 298.15 Kelvin
2. Program, to find the area of rectangle, square, circle and triangle by accepting suitable input parameters from user.
Syntax:
# Calculate the area of the triangle
area <- 0.5 * base * height
# Print the result
cat("The area of the triangle is:", area)
Example 1:
R
Output:
The area of the triangle is: 25
Output:
The area of the triangle is: 50
1
2for (num in 1:100) {
3 if (num %% 2 == 0) {
4 print(paste("Even number is :", num))
5}
6}
7
# Example usage
input <- 10
calculateSquare(input)
Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
6 squared is 36
7 squared is 49
8 squared is 64
9 squared is 81
10 squared is 100
# Example usage
input <- 10
output <- calculateSquaresVector(input)
print(output)
Output:
[1] 1 4 9 16 25 36 49 64 81 100
4. Write a program to join columns and rows in a data frame using cbind() and rbind() in R.
Let’s start by creating two vectors, having first and last names of players, by using following commands.
Using cbind() in R
The first function we are using is cbind() which essentially stands for column bind. This function is used to bind
vectors or matrices as columns to create a new matrix. So for the above vectors we just created, if we want to
combine them by column, the following command is used
It’s important to note that cbind() works element-wise, meaning it combines the elements of vectors or
matrices based on their positions in columns.
Using rbind() in R
Just like cbind() is used to combine columns of vectors or data frames, rbind() combines the rows of vectors or
data frames. It binds vectors, matrices, or data frames by rows to create a new vector, matrix, or data frame. Let’s
demonstrate it by using the above vectors created earlier. If we want the rows of above data set to be combined,
use the following command
Both data frame and vector has been created, let’s combine these by using following command
The above command combines vector with data frame in a single data set, as shown below.
Note that, in above commands, both data frame and vector are of same length, so they get combined smoothly.
It’s important to note that the resulting object consists of three vectors side by side, forming rows and columns.
These vectors combined above by the name of “three_vectors” can be converted into data frames by the
following command
three_vectors <- [Link](three_vectors)
For above data frames, football has 4 observations in each column, and basketball has three observations in each
column. Thus, the length of data set is different.
Now, if we combine these two data frames of different lengths; football and basketball, either by using rbind() or
cbind() function, the command wouldn’t run. Let’s try by using both commands as given below
missing_rbind <- rbind(basketball,football) missing_cbind <-
cbind(basketball,football)
The following error will be shown by the above commands. This implies that the length of data sets required to
combine should be same.
The only way to combine these data frames of different lengths is by using another function, bind_rows(). To use
this function, we first load the following library
library(dplyr)
The rbind() function appends the data set in a way that any missing columns in the shorter data frame are filled
with NA values, as shown in the above image.
Another way to combine these columns of different lengths is by using the merge() function. The merge function
is used for merging data frames based on common columns.
The following command shows how we can use merge() function to combine these columns of different lengths.
In the first two commands, row_no assigns unique row number to each row in the data frame. It creates a new
column called “row_no” in both the “football” and “basketball” data frames. The purpose of adding the
“row_no” column is to give each row a unique identifier so that the data frames can be merged based on these
identifiers. the next step is to merge these columns based on that unique identifier. The following output is
generated from the above command
Similarly, if you have vectors of different lengths, they should be assigned a same length or maximum length
of the vector, and then combine using cbind() or rbind() function. If three vectors have different length, then we
first find out the maximum length of the vector by using following command
m_len <- max(length(f_name), length(l_name),length(age))
The output shows that maximum length of above vectors is 3, so we assign same length to each of the above
vectors. Following commands should be used to serve the purpose
Once the same length has been assigned, next we combine these vectors by using either of the functions, as
shown in the command below
The above command combines vectors and save them by the name of diff_len.
Tweet
Share
Share
Pin
String Manipulation in R
Concatenation of Strings
String Concatenation is the technique of combining two strings. String
Concatenation can be done using many ways:
paste() function Any number of strings can be concatenated
together using the paste() function to form a larger string. This
function takes separator as argument which is used between the
individual string elements and another argument ‘collapse’ which
reflects if we wish to print the strings together as a single larger
string. By default, the value of collapse is NULL. Syntax:
paste(..., sep=" ", collapse = NULL)
Example:
Python3
Output:
"Learn Code"
In case no separator is specified the default separator ” ” is inserted
between individual strings. Example:
Python3
Output:
"1:4" "2:4" "3:4"
Since, the objects to be concatenated are of different lengths, a
repetition of the string of smaller length is applied with the other
input strings. The first string is a sequence of 1, 2, 3 which is then
individually concatenated with the other string “4” using separator
‘:’.
Python3
Output:
"1--5" "2--6" "3--7" "4--8"
Since, both the strings are of the same length, the corresponding
elements of both are concatenated, that is the first element of the
first string is concatenated with the first element of second-string
using the sep ‘–‘.
cat() function Different types of strings can be concatenated
together using the cat()) function in R, where sep specifies the
separator to give between the strings and file name, in case we wish
to write the contents onto a file. Syntax:
cat(..., sep=" ", file)
Example:
Python3
# R program for string concatenation
Output:
learn:code:techNULL
The output string is printed without any quotes and the default
separator is ‘:’.NULL value is appended at the end. Example:
Python3
Output:
1 2 3 4 5
The output is written to a text file [Link] in the same working directory.
Calculating Length of strings
length() function The length() function determines the number of
strings specified in the function. Example:
Python3
Output:
2
There are two strings specified in the function.
nchar() function nchar() counts the number of characters in each
of the strings specified as arguments to the function
individually. Example:
Python3
Output:
5 4
The output indicates the length of Learn and then Code separated
by ” ” .
Case Conversion of strings
Conversion to upper case All the characters of the strings
specified are converted to upper case. Example:
Python3
print (toupper(c("Learn Code", "hI")))
Output :
"LEARN CODE" "HI"
Conversion to lower case All the characters of the strings
specified are converted to lower case. Example:
Python3
Output :
"learn code" "hi"
casefold() function All the characters of the strings specified are
converted to lowercase or uppercase according to the arguments in
casefold(…, upper=TRUE). Examples:
Python3
Output:
"learn code" "hi"
By default, the strings get converted to lower case.
Python3
Output:
"LEARN CODE" "HI"
Character replacement
Characters can be translated using the chartr(oldchar, newchar, …) function
in R, where every instance of old character is replaced by the new character
in the specified set of strings. Example 1:
Python3
Output:
"An honest mAn gAve thAt"
Every instance of ‘a’ is replaced by ‘A’. Example 2:
Python3
Output:
"Th#@ #@ #t" "It #@ great"
Every instance of old string is replaced by new specified string. “i” is
replaced by “#” by “s” by “@”, that is the corresponding positions of old
string is replaced by new string. Example 3:
Python3
Output:
Error in chartr("ate", "#@", "I hate ate") : 'old' is longer than 'new'
Execution halted
The length of the old string should be less than the new string.
Splitting the string
A string can be split into corresponding individual strings using ” ” the
default separator. Example:
Python3
Output:
[1] "Learn" "Code" "Teach" "!"
Working with substrings
substr(…, start, end) or substring(…, start, end) function in R extracts
substrings out of a string beginning with the start index and ending with the
end index. It also replaces the specified substring with a new set of
characters. Example:
Python3
Output:
"Lear"
Extracts the first four characters from the string.
Python3
str & lt
- c(& quot
program", & quot
with"
, & quot
new"
, & quot
language"
)
substr(str, 3, 3) & lt
- & quot
% & quot
print(str)
Output:
"pr%gram" "wi%h" "ne%" "la%guage"
Replaces the third character of every string with % sign.
Python3
Output:
"pr%gram" "wi@h" "ne%" "la@guage"
6. Implement different data structures in R (Vectors, Lists, Data Frames)
#############################################
##########
# LESSON 3: VECTORS, LISTS, MATRICES, AND
DATA FRAMES #
# Christopher Jeruzal
#
# 09/09/2018
#
#############################################
##########
8 Write a program to read a csv file and analyze the data in the file in R.
BLACK FRIDAY SALE
Get Programiz PRO for LIFE at 60% off!
Claim My Discount
Sale ends in 00d : 02hrs : 08mins : 30s
TutorialsExamples Courses
Login to PRO
R Introduction
o
o
o
o
o
o
R Flow Control
o
o
o
o
o
o
o
o
R Data Structure
o
o
o
o
o
o
o
R Data Visualization
o
o
o
o
o
o
o
o
R Data Manipulation
R Additional Topics
o
o
o
o
R Tutorials
R has a built-in functionality that makes it easy to read and write a CSV file.
The CSV file above is a sample data of monthly air travel, in thousands of passengers,
for 1958-1960.
Now, let's try to read data from this CSV File using R's built-in functions.
Output
In the above example, we have read the [Link] file that is available in our
current directory. Notice the code,
read_data <- [Link]("[Link]")
Here, [Link]() reads the csv file [Link] and creates a dataframe which is
stored in the read_data variable.
Finally, the csv file is displayed using print() .
Note: If the file is in some other location, we have to specify the path along with the file
name as: [Link]("D:/folder1/[Link]") .
Output
Total Columns: 4
Total Rows: 12
In the above example, we have used the ncol() and nrow() function to find the total
number of columns and rows in the [Link] file.
Here,
Output
[1] 390
[1] 505
Here, we have used the min() and max() function to find the minimum and maximum
value of the 1960 and 1958 column of the [Link] file respectively.
min(read_data$1960) - returns the minimum value from the 1960 column i.e. 390
max(read_data$1958) - returns the maximum value from the 1958 column i.e. 505
print(sub_data)
Output
Month, 1958, 1959, 1960
6 JUN 435 472 535
7 JUL 491 548 622
8 AUG 505 559 606
9 SEP 404 463 508
Here, subset() creates a subset of [Link] with data column 1958 having data
greater than 400 and stored it in the sub_data data frame.
Since column 1958 has data greater than 400 in 6th, 7th, 8th, and 9th row, only these
rows are displayed.
In the above example, we have used the [Link]() function to export a data frame
named dataframe1 to a CSV file. Notice the arguments passed inside [Link]() ,
[Link](dataframe1, "[Link]")
Here,
[Link](dataframe1, "[Link]",
quote = FALSE
)
5
# Plot the chart.
6
pie(geeks, labels)
Output:
R – Pie Charts
5
# Plot the chart with title and rainbow
6
# color pallet.
7
pie(geeks, labels, main = "City pie chart",
8
col = rainbow(length(geeks)))
Output:
R – Pie Charts
slice percentage
o
o chart legend.
We can show the chart in the form of percentages as well as add
legends.
Example:
R
1
# Create data for the graph.
2
geeks <- c(23, 56, 20, 63)
3
labels <- c("Mumbai", "Pune", "Chennai", "Bangalore")
4
5
piepercent<- round(100 * geeks / sum(geeks), 1)
6
7
# Plot the chart.
8
pie(geeks, labels = piepercent,
9
main = "City pie chart", col = rainbow(length(geeks)))
10
legend("topright", c("Mumbai", "Pune", "Chennai", "Bangalore"),
11
cex = 0.5, fill = rainbow(length(geeks)))
Output:
R – Pie Charts
4
# Create data for the graph.
5
geeks <- c(23, 56, 20, 63)
6
labelss <- c("Mumbai", "Pune", "Chennai", "Bangalore")
7
8
labels<- [Link](length(geeks), "Set2")
9
10
pie(geeks, labels = labelss)
Output:
R – Pie Charts
modify the line type of the borders of the plot we can make use of
the lty argument:
R
1
Get the library.
2
library(RColorBrewer)
3
4
# Create data for the graph.
5
geeks <- c(23, 56, 20, 63)
6
labelss <- c("Mumbai", "Pune", "Chennai", "Bangalore")
7
8
labels<- [Link](length(geeks), "Set2")
9
10
pie(geeks, labels = labelss, col = color, lty = 2)
Output:
R – Pie Charts
4
# Create data for the graph.
5
geeks <- c(23, 56, 20, 63)
6
labelss <- c("Mumbai", "Pune", "Chennai", "Bangalore")
7
8
labels<- [Link](length(geeks), "Set2")
9
10
pie(geeks, labels = labelss,col = color, density = 50, angle = 45)
Output:
R – Pie Charts
3D Pie Chart
Here we are going to create a 3D Pie chart using plotrix package and then
we will use pie3D() function to plot 3D plot.
R
1
# Get the library.
2
library(plotrix)
3
4
# Create data for the graph.
5
geeks <- c(23, 56, 20, 63)
6
labels <- c("Mumbai", "Pune", "Chennai", "Bangalore")
7
8
piepercent<- round(100 * geeks / sum(geeks), 1)
9
10
# Plot the chart.
11
pie3D(geeks, labels = piepercent,
12
main = "City pie chart", col = rainbow(length(geeks)))
13
legend("topright", c("Mumbai", "Pune", "Chennai", "Bangalore"),
14
cex = 0.5, fill = rainbow(length(geeks)))
Output:
R – Pie Charts
Skip to content
Courses
Tutorials
Data Science
Practice
Sign In
Winter Tickets Sale!
Data Visualization
Statistics in R
Machine Learning in R
Data Science in R
Packages in R
Data Types
String
Array
Vector
Lists
Matrices
Oops in R
▲
160 Days of DSA
Share Your Experiences
R Tutorial | Learn R Programming Language
Introduction
Fundamentals of R
Variables
Input/Output
Control Flow
Functions
Data Structures
Object Oriented Programming
Error Handling
File Handling
Packages in R
Data Interfaces
Data Visualization
Statistics
o R - Statistics
o Mean, Median and Mode in R Programming
o Exploring Statistical Measures in R: Average, Variance, and Standard
Deviation Explained
o Descriptive Analysis in R Programming
o Normal Distribution in R
o Binomial Distribution in R Programming
o ANOVA (Analysis of Variance) Test in R Programming
o Covariance and Correlation in R Programming
o Skewness in R Programming
o Hypothesis Testing in R Programming
o Bootstrapping in R Programming
o Time Series Analysis in R
Machine Learning
DSA to DevelopmentCourse
R – Statistics
Last Updated : 12 Jul, 2024
R – Statistics
In the above code ‘?’ in front of a particular function means that it gives
information about that function with its syntax. In R ‘#’ is used for
commenting single line and there is no multiline comment in R Statistics.
Here we are using chickwts as the dataset and feed is the attribute in the
dataset.
Plots graph in decreasing order
Now we will plot graph in decreasing order in R Statistics.
R
1
feeds=table(chickwts$feed)
2
3
# plots graph in decreasing order
4
barplot(feeds[order(feeds, decreasing=TRUE)])
Output:
R – Statistics
3
# Set outside margins (bottom, left, top, right).
4
par(oma=c(1, 1, 1, 1))
5
par(mar=c(4, 5, 2, 1))
6
7
# Use las for the orientation of axis labels.
8
barplot(feeds[order(feeds, decreasing=TRUE)],
9
xlab="Number of chicks", las=1, col="yellow")
10
11
# Use horiz for bars to be shown as horizontal.
12
barplot(feeds[order(feeds)], horiz=TRUE,
13
xlab="Number of chicks", las=1, col="yellow")
Output:
R – Statistics
Pie charts
A pie chart is a circular statistical graph that is divided into slices to show
the different sizes of the data.
R
1
data("chickwts")
2
3
# main is used to create
4
# an heading for the chart
5
d = table(chickwts$feed)
6
7
pie(d[order(d, decreasing=TRUE)],
8
clockwise=TRUE,
9
main="Pie Chart of feeds from chichwits", )
Output:
R – Statistics
Histograms
Histograms are the representation of the distribution of data(numerical or
categorical). in R Statistics It is similar to a bar chart but it groups data in
terms of ranges.
R
1
# break is used for number of bins.
2
data(lynx)
3
4
# lynx is a built-in dataset.
5
lynx
6
7
# hist function is used to plot histogram.
8
hist(lynx)
9
hist(lynx, col="green",
10
main="Histogram of Annual Canadian Lynx Trappings")
Output :
Time Series:
Start = 1821
End = 1934
Frequency = 1
[1] 269 321 585 871 1475 2821 3928 5943 4950 2577 523 98 184
[14] 279 409 2285 2685 3409 1824 409 151 45 68 213 546 1033
[27] 2129 2536 957 361 377 225 360 731 1638 2725 2871 2119 684
[40] 299 236 245 552 1623 3311 6721 4254 687 255 473 358 784
[53] 1594 1676 2251 1426 756 299 201 229 469 736 2042 2811 4431
[66] 2511 389 73 39 49 59 188 377 1292 4031 3495 587 105
[79] 153 387 758 1307 3465 6991 6313 3794 1836 345 382 808 1388
[92] 2713 3800 3091 2985 3790 674 81 80 108 229 399 1132 2432
[105] 3574 2935 1537 529 485 662 1000 1590 2657 3396
R – Statistics
3
# if freq=FALSE this will draw normal distribution
4
hist(lynx)
5
hist(lynx,col="green",
6
freq=FALSE ,main="Histogram of Annual Canadian Lynx Trappings")
7
8
curve(dnorm(x, mean=mean(lynx),
9
sd=sd(lynx)), col="red",
10
lwd=2, add=TRUE)
Output:
R – Statistics
Box Plots
Box Plot is a function for graphically depicting groups of numerical data
using quartiles. In R Statistics It represents the distribution of data and
understanding mean, median, and variance.
R
1
# USJudgeRatings is Built-in Dataset.
2
?USJudgeRatings
3
4
# ylim is used to specify the range.
5
boxplot(USJudgeRatings$RTEN, horizontal=TRUE,
6
xlab="Lawyers Rating", notch=TRUE,
7
ylim=c(0, 10), col="pink")
Output:
R – Statistics
# Example usage
numbers <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
result <- count_even_odd(numbers)
cat("Even numbers:", result$even, "\n")
cat("Odd numbers:", result$odd, "\n")
MACHINE LEARNING LAB
Skip to content
Courses
Tutorials
Data Science
Practice
Sign In
Winter Tickets Sale!
AI ML DS
Data Science
Data Analysis
Data Visualization
Machine Learning
Deep Learning
NLP
Computer Vision
Artificial Intelligence
AI ML DS Interview Series
AI ML DS Projects series
Data Engineering
Web Scrapping
▲
160 Days of DSA
Share Your Experiences
Machine Learning Algorithms
Top 15 Machine Learning Algorithms Every Data Scientist Should Know in 2024
Linear Model Regression
Linear Model Classification
Regularization
K-Nearest Neighbors (KNN)
Support Vector Machines
ML | Stochastic Gradient Descent (SGD)
Decision Tree
o Major Kernel Functions in Support Vector Machine (SVM)
o CART (Classification And Regression Tree) in Machine Learning
o Decision Tree Classifiers in R Programming
o Python | Decision Tree Regression using sklearn
Ensemble Learning
Generative Model
Time Series Forecasting
Supervised Dimensionality Reduction Technique
Metrics for Classification & Regression Algorithms
Cross Validation Technique
Optimization Technique
Clustering
Association Rule Mining
Anomaly Detection
Dimensionality Reduction Technique
Model-Based Methods
Model-Free Methods
Asynchronous Advantage Actor Critic (A3C) algorithm
Machine Learning & Data ScienceCourse
Python | Decision Tree Regression using
sklearn
Last Updated : 11 Jan, 2023
# import dataset
# dataset = pd.read_csv('[Link]')
# alternatively open up .csv file to read data
dataset = [Link](
[['Asset Flip', 100, 1000],
['Text Based', 500, 3000],
['Visual Novel', 1500, 5000],
['2D Pixel Art', 3500, 8000],
['2D Vector Art', 5000, 6500],
['Strategy', 6000, 7000],
['First Person Shooter', 8000, 15000],
['Simulator', 9500, 20000],
['Racing', 12000, 21000],
['RPG', 14000, 25000],
['Sandbox', 15500, 27000],
['Open-World', 16500, 30000],
['MMOFPS', 25000, 52000],
['MMORPG', 30000, 80000]
])
Output:
[['Asset Flip' '100' '1000']
['Text Based' '500' '3000']
['Visual Novel' '1500' '5000']
['2D Pixel Art' '3500' '8000']
['2D Vector Art' '5000' '6500']
['Strategy' '6000' '7000']
['First Person Shooter' '8000' '15000']
['Simulator' '9500' '20000']
['Racing' '12000' '21000']
['RPG' '14000' '25000']
['Sandbox' '15500' '27000']
['Open-World' '16500' '30000']
['MMOFPS' '25000' '52000']
['MMORPG' '30000' '80000']]
Step 3: Select all the rows and column 1 from the dataset to “X”.
Python3
# print X
print(X)
Output:
[[ 100]
[ 500]
[ 1500]
[ 3500]
[ 5000]
[ 6000]
[ 8000]
[ 9500]
[12000]
[14000]
[15500]
[16500]
[25000]
[30000]]
Step 4: Select all of the rows and column 2 from the dataset to “y”.
Python3
# print y
print(y)
Output:
[ 1000 3000 5000 8000 6500 7000 15000 20000 21000 25000 27000 30000
52000 80000]
Step 5: Fit decision tree regressor to the dataset
Python3
# import the regressor
from [Link] import DecisionTreeRegressor
Output:
DecisionTreeRegressor(ccp_alpha=0.0, criterion='mse', max_depth=None,
max_features=None, max_leaf_nodes=None,
min_impurity_decrease=0.0,
min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0,
presort='deprecated',
random_state=0, splitter='best')
Step 6: Predicting a new value
Python3
Output:
Predicted price: 8000
Step 7: Visualising the result
Python3
# specify title
[Link]('Profit to Production Cost (Decision Tree Regression)')
# import export_graphviz
from [Link] import export_graphviz
Below are some assumptions that we made while using the decision tree:
At the beginning, we consider the whole training set as the root.
Feature values are preferred to be categorical. If the values are
continuous then they are discretized prior to building the model.
On the basis of attribute values, records are distributed recursively.
We use statistical methods for ordering attributes as root or the
internal node.
As you can see from the above image the Decision Tree works on the Sum
of Product form which is also known as Disjunctive Normal Form. In the
above image, we are predicting the use of computer in the daily life of
people. In the Decision Tree, the major challenge is the identification of the
attribute for the root node at each level. This process is known as attribute
selection. We have two popular attribute selection measures:
1. Information Gain
2. Gini Index
1. Information Gain:
When we use a node in a decision tree to partition the training instances into
smaller subsets the entropy changes. Information gain is a measure of this
change in entropy.
Suppose S is a set of instances,
A is an attribute
Sv is the subset of S
v represents an individual value that the attribute A can take and
Values (A) is the set of all possible values of A, then
Gain(S,A)=Entropy(S)–∑vA∣Sv∣∣S∣.Entropy(Sv)Gain(S,A)=Entropy(S)–∑vA∣S∣∣Sv∣
.Entropy(Sv)
Entropy: is the measure of uncertainty of a random variable, it
characterizes the impurity of an arbitrary collection of examples. The higher
the entropy more the information content.
Suppose S is a set of instances, A is an attribute, S v is the subset of S with A
= v, and Values (A) is the set of all possible values of A, then
Gain(S,A)=Entropy(S)–∑vϵValues(A)∣Sv∣∣S∣.Entropy(Sv) Gain(S,A)=Entropy(S)–∑vϵValues(A)∣S∣∣Sv∣
.Entropy(Sv)
Example:
For the set X = {a,a,a,b,b,b,b,b}
Total instances: 8
Instances of b: 5
Instances of a: 3
Entropy H(X)=[(38)log238+(58)log258]=−[0.375(−1.415)+0.625(−0.678)]=−
(−0.53−0.424)=0.954Entropy H(X)=[(83)log283+(85)log285]=−[0.375(−1.415)+0.625(−0.678)]=−
(−0.53−0.424)=0.954
Building Decision Tree using Information Gain The essentials:
Start with all training instances associated with the root node
Use info gain to choose which attribute to label each node with
Note: No root-to-leaf path should contain the same discrete attribute
twice
Recursively construct each subtree on the subset of training
instances that would be classified down that path in the tree.
If all positive or all negative training instances remain, the label that
node “yes” or “no” accordingly
If no attributes remain, label with a majority vote of training
instances left at that node
If no instances remain, label with a majority vote of the parent’s
training instances.
Example: Now, let us draw a Decision Tree for the following data using
Information gain. Training set: 3 features and 2 classes
X Y Z C
1 1 1 I
1 1 0 I
0 0 1 II
1 0 0 II
Here, we have 3 features and 2 output classes. To build a decision tree using
Information gain. We will take each of the features and calculate the
information for each feature.
Split on feature X
Split on feature Y
Split on feature Z
From the above images, we can see that the information gain is maximum
when we make a split on feature Y. So, for the root node best-suited feature
is feature Y. Now we can see that while splitting the dataset by feature Y,
the child contains a pure subset of the target variable. So we don’t need to
further split the dataset. The final tree for the above dataset would look like
this:
2. Gini Index
Gini Index is a metric to measure how often a randomly chosen
element would be incorrectly identified.
It means an attribute with a lower Gini index should be preferred.
Sklearn supports “Gini” criteria for Gini Index and by default, it takes
“gini” value.
The Formula for the calculation of the Gini Index is given below.
The Formula for Gini Index is given by :
Gini Impurity
[Link]
ts as sts
import numpy as np
import [Link] as plt
import numpy as np
from sklearn.linear_model import BayesianRidge
print(predictions)
5. Bagging in Classification
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
from [Link] import StandardScaler
from sklearn.linear_model import LogisticRegression
from [Link] import make_pipeline
from [Link] import BaggingClassifier
from sklearn.model_selection import GridSearchCV
#
# Load the breast cancer dataset
#
bc = datasets.load_breast_cancer()
X = [Link]
y = [Link]
#
# Create training and test split
#
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25,
random_state=1, stratify=y)
#
# Pipeline Estimator
#
pipeline = make_pipeline(StandardScaler(),
LogisticRegression(random_state=1))
#
# Fit the model
#
[Link](X_train, y_train)
#
# Model scores on test and training data
#
print('Model test Score: %.3f, ' %[Link](X_test, y_test),
'Model training Score: %.3f' %[Link](X_train, y_train))
Typically, the number of trees is increased until the model performance stabilizes. Intuition might
suggest that more trees will lead to overfitting, although this is not the case. Bagging and related
ensemble of decision trees algorithms (like random forest) appear to be somewhat immune to
overfitting the training dataset given the stochastic nature of the learning algorithm.
The number of trees can be set via the “n_estimators” argument and defaults to 100.
The example below explores the effect of the number of trees with values between 10 to 5,000.
Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or
differences in numerical precision. Consider running the example a few times and compare the
average outcome.
In this case, we can see that that performance improves on this dataset until about 100 trees and
remains flat after that.
We can see the general trend of no further improvement beyond about 100 trees.
7. Data & Text Classification using Neural Networks
import numpy as np
model = Sequential()
[Link](Embedding(maximum_features, word_embedding_dims,
input_length=maximum_length))
# Adding the 1D convolutional layer with ReLU activation
activation='relu', strides=1))
[Link](GlobalMaxPooling1D())
[Link](Dense(hidden_dims, activation='relu'))
# Adding the output layer with sigmoid activation for binary classification
[Link](Dense(1, activation='sigmoid'))
# Compiling the model with binary cross-entropy loss and Adam optimizer
[Link](loss='binary_crossentropy',
optimizer='adam', metrics=['accuracy'])
y_pred_prob = [Link](x_test)
f1 = f1_score(y_test, y_pred)
# Printing the evaluation metrics
print('Accuracy:', accuracy)
print('Precision:', precision)
print('Recall:', recall)
print('F1-score:', f1)
Epoch 1/2
782/782 [==============================] - 7s 8ms/step - loss: 0.4245 -
accuracy: 0.7927 - val_loss: 0.3713 - val_accuracy: 0.8320
Epoch 2/2
782/782 [==============================] - 7s 9ms/step - loss: 0.2521 -
accuracy: 0.8971 - val_loss: 0.3251 - val_accuracy: 0.8583
782/782 [==============================] - 2s 2ms/step
Accuracy: 0.85832
Precision: 0.8426931905126244
Recall: 0.88112
F1-score: 0.8614782948768088
8. Using Weka tool for SVM classification for chosen domain application
# plotting scatter
[Link](X[:, 0], X[:, 1], c=Y, s=50, cmap='spring')
[Link](-1, 3.5);
[Link]()
Importing datasets
This is the intuition of support vector machines, which optimize a linear
discriminant model representing the perpendicular distance between the
datasets. Now let’s train the classifier using our training data. Before
training, we need to import cancer datasets as csv file where we will train
two features out of all features.
python3
print (x),(y)
[[ 122.8 1001. ]
[ 132.9 1326. ]
[ 130. 1203. ]
...,
[ 108.3 858.1 ]
[ 140.1 1265. ]
[ 47.92 181. ]]
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 1., 1., 1., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0.,
0., 0., 0., 0., 0., 0., 0., 1., 0., 1., 1., 1., 1.,
1., 0., 0., 1., 0., 0., 1., 1., 1., 1., 0.,
1., ....,
1.])
Fitting a Support Vector Machine
Now we’ll fit a Support Vector Machine Classifier to these points. While the
mathematical details of the likelihood model are interesting, we’ll let read
about those elsewhere. Instead, we’ll just treat the scikit-learn algorithm as
a black box which accomplishes the above task.
python3
After being fitted, the model can then be used to predict new values:
python3
[Link]([[120, 990]])
[Link]([[85, 550]])
array([ 0.])
array([ 1.])
Let’s have a look on the graph how does this show.
Image by author.
Figure 2: The data points are segmented into groups denoted with
differing colors.
Algorithm
For a given dataset, k is specified to be the number of distinct
groups the points belong to. These k centroids are first randomly
initialized, then iterations are performed to optimize the locations of
these k centroids as follows:
Data
To evaluate our algorithm, we’ll first generate a dataset of groups in
2-dimensional space. The [Link] function make_blobs
creates groupings of 2-dimensional normal distributions, and
assigns a label corresponding to the group said point belongs to.
import seaborn as sns
from [Link] import make_blobs
import [Link] as plt
from [Link] import StandardScalercenters = 5
X_train, true_labels = make_blobs(n_samples=100, centers=centers,
random_state=42)
X_train = StandardScaler().fit_transform(X_train)[Link](x=[X[0]
for X in X_train],
y=[X[1] for X in X_train],
hue=true_labels,
palette="deep",
legend=None
)[Link]("x")
[Link]("y")
[Link]()
Image by author.
Model Creation
Helper Functions
We’ll need to calculate the distances between a point and a dataset
of points multiple times in this algorithm. To do so, lets define a
function that calculates Euclidean distances.
def euclidean(point, data):
"""
Euclidean distance between point & data.
Point has dimensions (m,), data has dimensions (n,m), and output will
be of size (n,).
"""
return [Link]([Link]((point - data)**2, axis=1))
Implementation
First, the k-means clustering algorithm is initialized with a value for
k and a maximum number of iterations for finding the optimal
centroid locations. If a maximum number of iterations is not
considered when optimizing centroid locations, there is a risk of
running an infinite loop.
class KMeans: def __init__(self, n_clusters=8, max_iter=300):
self.n_clusters = n_clusters
self.max_iter = max_iter
Now, the bulk of the algorithm is performed when fitting the model
to a training dataset.
First we’ll initialize the centroids randomly in the domain of the test
dataset, with a uniform distribution.
# Randomly select centroid start points, uniformly distributed across the
domain of the dataset
min_, max_ = [Link](X_train, axis=0), [Link](X_train, axis=0)
[Link] = [uniform(min_, max_) for _ in range(self.n_clusters)]
Before beginning the while loop, we’ll initialize the variables used in
the exit conditions.
iteration = 0
prev_centroids = None
Now, we begin the loop. We’ll iterate through the data points in the
training set, assigning them to an initialized empty list of lists. The
sorted_points list contains one empty list for each centroid, where
data points are appended once they’ve been assigned.
while np.not_equal([Link], prev_centroids).any() and iteration <
self.max_iter:
# Sort each data point, assigning to nearest centroid
sorted_points = [[] for _ in range(self.n_clusters)]
for x in X_train:
dists = euclidean(x, [Link])
centroid_idx = [Link](dists)
sorted_points[centroid_idx].append(x)
Now that we’ve assigned the whole training dataset to their closest
centroids, we can update the location of the centroids and finish the
iteration.
# Push current centroids to previous, reassign centroids as mean of the
points belonging to them
prev_centroids = [Link]
[Link] = [[Link](cluster, axis=0) for cluster in
sorted_points]
for i, centroid in enumerate([Link]):
if [Link](centroid).any(): # Catch any [Link], resulting from a
centroid having no points
[Link][i] = prev_centroids[i]
iteration += 1
Image by author.
If we run this new model a few times we’ll see it performs much
better, but still not always perfect.
Image by author.
Conclusion
And with that, we’re finished. We learned a simple, yet elegant
implementation of an unsupervised machine learning model. The
complete project code is included below.
import numpy as np
import [Link] as plt
from [Link] import StandardScaler
from [Link] import uniform
from [Link] import make_blobs
import seaborn as sns
import random
def euclidean(point, data):
"""
Euclidean distance between point & data.
Point has dimensions (m,), data has dimensions (n,m), and output will
be of size (n,).
"""
return [Link]([Link]((point - data)**2, axis=1))
class KMeans: def __init__(self, n_clusters=8, max_iter=300):
self.n_clusters = n_clusters
self.max_iter = max_iter def fit(self, X_train): #
Initialize the centroids, using the "k-means++" method, where a random
datapoint is selected as the first,
# then the rest are initialized w/ probabilities proportional to
their distances to the first
# Pick a random point from train data for first centroid
[Link] = [[Link](X_train)] for _ in
range(self.n_clusters-1):
# Calculate distances from points to the centroids
dists = [Link]([euclidean(centroid, X_train) for centroid in
[Link]], axis=0)
# Normalize the distances
dists /= [Link](dists)
# Choose remaining points based on their distances
new_centroid_idx, = [Link](range(len(X_train)),
size=1, p=dists)
[Link] += [X_train[new_centroid_idx]] # This
initial method of randomly selecting centroid starts is less effective
# min_, max_ = [Link](X_train, axis=0), [Link](X_train, axis=0)
# [Link] = [uniform(min_, max_) for _ in
range(self.n_clusters)] # Iterate, adjusting centroids until
converged or until passed max_iter
iteration = 0
prev_centroids = None
while np.not_equal([Link], prev_centroids).any() and
iteration < self.max_iter:
# Sort each datapoint, assigning to nearest centroid
sorted_points = [[] for _ in range(self.n_clusters)]
for x in X_train:
dists = euclidean(x, [Link])
centroid_idx = [Link](dists)
sorted_points[centroid_idx].append(x) # Push
current centroids to previous, reassign centroids as mean of the points
belonging to them
prev_centroids = [Link]
[Link] = [[Link](cluster, axis=0) for cluster in
sorted_points]
for i, centroid in enumerate([Link]):
if [Link](centroid).any(): # Catch any [Link],
resulting from a centroid having no points
[Link][i] = prev_centroids[i]
iteration += 1 def evaluate(self, X):
centroids = []
centroid_idxs = []
for x in X:
dists = euclidean(x, [Link])
centroid_idx = [Link](dists)
[Link]([Link][centroid_idx])
centroid_idxs.append(centroid_idx) return centroids,
centroid_idxs
# Create a dataset of 2D distributions
centers = 5
X_train, true_labels = make_blobs(n_samples=100, centers=centers,
random_state=42)
X_train = StandardScaler().fit_transform(X_train)# Fit centroids to dataset
kmeans = KMeans(n_clusters=centers)
[Link](X_train)# View results
class_centers, classification = [Link](X_train)
[Link](x=[X[0] for X in X_train],
y=[X[1] for X in X_train],
hue=true_labels,
style=classification,
palette="deep",
legend=None
)
[Link]([x for x, _ in [Link]],
[y for _, y in [Link]],
'k+',
markersize=10,
)[Link]()
Apr 9, 2022
29
In
by
Benjamin Etienne
1d ago
341
4
In
by
W Brett Kennedy
1d ago
406
9
In
by
Turner Luke
May 2, 2022
99
1
In
Stackademic
by
Abdur Rahman
Oct 23
8.2K
32
Raphael Schols
May 31
8
In
by
89
1
Amit Yadav
Jul 18
10. Data & Text Clustering using Gaussian Mixture Models
Master Generative AI: Your step-by-step guide to become a Certified GenAI expert
Download Roadmap
Free Courses
Learning Paths
GenAI Pinnacle Program
Agentic AI Pioneer ProgramNew
Login
Interview Prep
Career
GenAI
Prompt Engg
ChatGPT
LLM
Langchain
RAG
AI Agents
Machine Learning
Deep Learning
GenAI Tools
LLMOps
Python
NLP
SQL
AIML Projects
READING LIST
Basics of Machine Learning
Machine Learning Lifecycle
Importance of Stats and EDA
Understanding Data
Probability
Exploring Continuous Variable
Exploring Categorical Variables
Missing Values and Outliers
Central Limit theorem
Bivariate Analysis Introduction
Continuous - Continuous Variables
Continuous Categorical
Categorical Categorical
Multivariate Analysis
Different tasks in Machine Learning
Build Your First Predictive Model
Evaluation Metrics
Preprocessing Data
Linear Models
KNN
Selecting the Right Model
Feature Selection Techniques
Decision Tree
Feature Engineering
Naive Bayes
Multiclass and Multilabel
Basics of Ensemble Techniques
Advance Ensemble Techniques
Hyperparameter Tuning
Support Vector Machine
Advance Dimensionality Reduction
Unsupervised Machine Learning Methods
Introduction to ClusteringApplications of ClusteringEvaluation Metrics for ClusteringUnderstanding K-
MeansImplementation of K-Means in PythonImplementation of K-Means in RChoosing Right Value for
KProfiling Market Segments using K-Means ClusteringHierarchical ClusteringImplementation of
Hierarchial ClusteringDBSCANDefining Similarity between clustersBuild Better and Accurate Clusters
with Gaussian Mixture Models
Recommendation Engines
Improving ML models
Working with Large Datasets
Interpretability of Machine Learning Models
Interpretability of Machine Learning Models
Automated Machine Learning
Model Deployment
Deploying ML Models
Embedded Devices
1. Home
2. Algorithm
Overview
Understand how Gaussian Mixture Models work and how to implement them in Python
We’ll also cover the k-means clustering algorithm and see how Gaussian Mixture Models improve
on it
Introduction
I really like working on unsupervised learning problems. They offer a completely different challenge to a
supervised learning problem – there’s much more room for experimenting with the data that I have. It’s no
wonder that the majority of developments and breakthroughs in the machine learning space are happening in
And one of the most popular techniques in unsupervised learning is clustering. It’s a concept we typically
learn early on in our machine learning journey and it’s simple enough to grasp. I’m sure you’ve come across
or even worked on projects like customer segmentation, market basket analysis, etc.
But here’s the thing – clustering has many layers. It isn’t limited to the basic algorithms we learned earlier.
It is a powerful unsupervised learning technique that we can use in the real-world with unerring accuracy.
Gaussian Mixture Models are one such clustering algorithm that I want to talk about in this article.
Want to forecast the sales of your favorite product? Or perhaps you want to understand customer churn
through the lens of different groups of customers. Whatever the use case, you’ll find Gaussian Mixture
We’ll take a bottom-top approach in this article. So, we’ll first look at the basics of clustering including a
quick recap of the k-means algorithm. Then, we’ll dive into the concept of Gaussian Mixture Models and
Table of contents
1. Introduction
2. Introduction to Clustering
8. What is Expectation-Maximization?
o E-step
o M-step
Introduction to Clustering
Before we kick things off and get into the nitty-gritty of Gaussian Mixture Models, let’s quickly refresh
Note: If you are already familiar with the idea behind clustering and how the k-means clustering algorithm
works, you can directly skip to the fourth section, ‘Introduction to Gaussian Mixture Models’.
Clustering refers to grouping similar data points together, based on their attributes or features.
For example, if we have the income and expenditure for a set of people, we can divide them into the
following groups:
Each of these groups would hold a population with similar features and can be useful in pitching the relevant
scheme/product to the group. Think of credit cards, car/property loans, and so on. In simple words:
The idea behind clustering is grouping data points together, such that each individual cluster holds the most
similar points.
There are various clustering algorithms out there. One of the most popular clustering algorithms is k-means.
Let us understand how the k-means algorithm works and what are the possible scenarios where this
k-means clustering is a distance-based algorithm. This means that it tries to group the closest points to form
a cluster.
Let’s take a closer look at how this algorithm works. This will lay the foundational blocks to help you
understand where Gaussian Mixture Models will come into play later in this article.
So, we first define the number of groups that we want to divide the population into – that’s the value of k.
Based on the number of clusters or groups we want, we then randomly initialize k centroids.
The data points are then assigned to the closest centroid and a cluster is formed. The centroids are then
updated and the data points are reassigned. This process goes on iteratively until the location of centroids no
longer changes.
Note: This was a brief overview of k-means clustering and is good enough for this article. If you want to go
deeper into the working of the k-means algorithm, here is an in-depth guide: The Most Comprehensive
The k-means clustering concept sounds pretty great, right? It’s simple to understand, relatively easy to
implement, and can be applied in quite several use cases. But there are certain drawbacks and limitations
Let’s take the same income-expenditure example we saw above. The K-means algorithm seems to be
working pretty well, right? Hold on – if you look closely, you will notice that all the clusters created are
circular. This is because the centroids of the clusters are updated iteratively using the mean value.
Now, consider the following example where the distribution of points is not circular. What do you think will
happen if we use k-means clustering on this data? It would still attempt to group the data points circularly.
Hence, we need a different way to assign clusters to the data points. So instead of using a distance-based
model, we will now use a distribution-based model. And that is where Gaussian Mixture Models come
The Gaussian Mixture Model (GMM) is a probabilistic model used for clustering and density estimation. It
assumes that the data is generated from a mixture of several Gaussian components, each representing a
distinct cluster. GMM assigns probabilities to data points, allowing them to belong to multiple clusters
simultaneously. The model is widely used in machine learning and pattern recognition applications.
Gaussian Mixture Models (GMMs) assume that there are a certain number of components, where each
component is a Gaussian distribution. Hence, a Gaussian Mixture Model tends to group the data points
belonging to a single Gaussian component together. The parameters of the mixture components, such as the
means and covariances, are typically estimated using the Expectation-Maximization (EM) algorithm or
Let’s say we have three Gaussian components (more on that in the next section) – GD1, GD2, and GD3.
These have a certain mean (μ1, μ2, μ3) and variance (σ1, σ2, σ3) value respectively. For a given set of data
points, our GMM would identify the probability of each data point belonging to each of these mixture
components. The EM algorithm iteratively updates these parameters to maximize the likelihood of the data,
Wait, probability?
You read that right! Gaussian Mixture Models are probabilistic models and use the soft clustering
approach for distributing the points in different clusters. I’ll take another example that will make it
easier to understand.
Here, we have three clusters that are denoted by three colors – Blue, Green, and Cyan. Let’s take the data
point highlighted in red. The probability of this point being a part of the blue cluster is 1, while the
the cluster assignments given the data. An important decision in GMMs is choosing the appropriate number
of components, which can be done using techniques like the Bayesian Information Criterion (BIC) or cross-
validation.
Now, consider another point – somewhere in between the blue and cyan (highlighted in the below figure).
The probability that this point is a part of cluster green is 0, right? The probability that this belongs to blue
and cyan is 0.2 and 0.8 respectively. These coefficients represent the responsibilities or soft assignments of
distributions, leveraging Bayes’ theorem to compute the posterior probabilities. I’m sure you’re wondering
what these distributions are so let me explain that in the next section.
I’m sure you’re familiar with Gaussian Distributions (or the Normal Distribution). It has a bell-shaped
curve, with the data points symmetrically distributed around the mean value.
The below image has a few Gaussian distributions with a difference in mean (μ) and variance (σ 2 ).
In a one dimensional space, the probability density function of a Gaussian distribution is given by:
But this would only be true for a single variable. In the case of two variables, instead of a 2D bell-shaped
where x is the input vector, μ is the 2D mean vector, and Σ is the 2×2 covariance matrix. The covariance
would now define the shape of this curve. We can generalize the same for d-dimensions.
Thus, this multivariate Gaussian model would have x and μ as vectors of length d, and Σ would be a d x
d covariance matrix.
Hence, for a dataset with d features, we would have a mixture of k Gaussian distributions (where k is
equivalent to the number of clusters), each having a certain mean vector and variance matrix. But wait –
how is the mean and variance value for each Gaussian assigned?
These values are determined using a technique called expectation maximization (EM). We need to
understand this technique before we dive deeper into the working of Gaussian Mixture Models.
What is Expectation-Maximization?
Excellent question!
Expectation-Maximization (EM) is a statistical algorithm for finding the right model parameters. We
typically use EM when the data has missing values, or in other words, when the data is incomplete.
These missing variables are called latent variables. We consider the target (or cluster number) to be
It’s difficult to determine the right model parameters due to these missing variables. Think of it this way – if
you knew which data point belongs to which cluster, you would easily be able to determine the mean vector
Since we do not have the values for the latent variables, expectation-maximization tries to use the
existing data to determine the optimum values for these variables and then finds the model
parameters. Based on these model parameters, we go back and update the values for the latent variable, and
so on.
E-step: In this step, the available data is used to estimate (guess) the values of the missing variables
M-step: Based on the estimated values generated in the E-step, the complete data is used to update
the parameters
Expectation-Maximization is the base of many algorithms, including Gaussian Mixture Models. So how
does GMM use the concept of EM and how can we apply it for a given set of points? Let’s find out!
Let’s understand this using another example. I want you to visualize the idea in your mind as you read
along. This will help you better understand what we’re talking about.
Let’s say we need to assign k number of clusters. This means that there are k Gaussian distributions, with
the mean and covariance values to be μ1, μ2, .. μk and Σ1, Σ2, .. Σk. Additionally, there is another parameter
for the distribution that defines the number of points for the distribution. In other words, the density of the
distribution is represented with Πi, capturing the relative sizes of different subpopulations.
Now, we need to find the values for these parameters to define the Gaussian distributions. We already
decided on the number of clusters and randomly assigned the values for the mean, covariance, and density.
Next, we’ll perform the expectation step (E-step) and the maximization step (M-step) iteratively!
In the E-step, we compute the probability of each data point belonging to each of the k Gaussian
components, given the current parameter values. Then, in the M-step, we re-estimate the parameters (means,
covariances, and component weights) to maximize the likelihood of the data, using the responsibilities
computed in the E-step. This optimization process continues until convergence or a maximum number of
iterations is reached. Advanced techniques like variational inference can also be used for parameter
For each point x i, calculate the probability that it belongs to cluster/distribution c 1, c 2, … c k. This is done
This value will be high when the point is assigned to the right cluster and lower otherwise.
M-step
Post the E-step, we go back and update the Π, μ and Σ values. These are updated in the following manner:
1. The new density is defined by the ratio of the number of points in the cluster and the total number of
points:
2. The mean and the covariance matrix are updated based on the values assigned to the distribution, in
proportion with the probability values for the data point. Hence, a data point that has a higher
and update the values iteratively. This process is repeated in order to maximize the log-likelihood function.
k-means only considers the mean to update the centroid while GMM takes into account the mean as well as
It’s time to dive into the code! This is one of my favorite parts of any article so let’s get going straightaway.
We’ll start by loading the data. This is a temporary file that I have created – you can download the data
Python Code:
import pandas as pd
import [Link] as plt
data = pd.read_csv('Clustering_gmm.csv')
[Link](figsize=(7,7))
[Link](data["Weight"],data["Height"])
[Link]('Weight')
[Link]('Height')
[Link]('Data Distribution')
[Link]()Copy Code
That’s what our data looks like. Let’s build a k-means model on this data first:
#training k-means model
from [Link] import KMeans
kmeans = KMeans(n_clusters=4)
[Link](data)
#plotting results
color=['blue','green','cyan', 'black']
for k in range(0,4):
data = frame[frame["cluster"]==k]
[Link](data["Weight"],data["Height"],c=color[k])
[Link]()
view rawbuilding_kmeans.py hosted with ❤ by GitHub
That’s not quite right. The k-means model failed to identify the right clusters. Look closely at the clusters in
the center – k-means has tried to build a circular cluster even though the data distribution is elliptical
Let’s now build a Gaussian Mixture Model on the same data and see if we can improve on k-means:
import pandas as pd
data = pd.read_csv('Clustering_gmm.csv')
color=['blue','green','cyan', 'black']
for k in range(0,4):
data = frame[frame["cluster"]==k]
[Link](data["Weight"],data["Height"],c=color[k])
[Link]()
view rawgaussian_mixture_model.py hosted with ❤ by GitHub
Excellent! Those are exactly the clusters we were hoping for. Gaussian Mixture Models have blown k-
End Notes
This was a beginner’s guide to Gaussian Mixture Models. My aim here was to introduce you to this
powerful clustering technique and showcase how effective and efficient it can be as compared to your
traditional algorithms.
Decision trees are suitable for both classification and regression due to their hierarchical structure and ability to make decisions based on input data attributes. For classification, they determine the class label by traversing nodes and evaluating attribute values, effectively making decisions based on different conditions . In regression tasks, decision trees predict continuous values by averaging the output variable in the leaf nodes. Their interpretability and capability to handle both numerical and categorical data make them versatile for various tasks .
The k-means++ initialization method improves the traditional k-means clustering by selecting the first centroid randomly and then each subsequent centroid with a probability proportional to the distance from the closest existing centroid . This reduces the chances of poor clustering caused by unlucky initializations where centroids are too close to each other or isolated from data points . It significantly decreases the likelihood of the algorithm getting stuck in local minima, thus often leading to better results and faster convergence .
Uniform distribution for initial centroid selection in k-means clustering helps ensure that centroids are spread across the entire data space, preventing them from being concentrated in one region . However, this method doesn't account for data density and can place centroids far from any data points, leading to slow convergence or suboptimal solutions . These limitations are partially mitigated by the k-means++ initialization, which considers data distribution when selecting centroids, improving convergence speed and clustering quality .
Pruning in decision trees involves removing branches that have little significance and do not provide much predictive power, thus reducing model complexity. Pruning enhances model performance by preventing overfitting; it removes parts of the tree that capture noise in the training data . This reduction in complexity helps maintain generalization by focusing on the most important decision paths, thus improving predictive accuracy on unseen data .
In Gaussian Mixture Models, the EM algorithm is used to iteratively refine the parameters of the mixture components. During the E-step, it computes the probability (responsibility) that each data point belongs to each Gaussian based on current parameters. In the M-step, it updates the parameters (mean, covariance, and weight of each Gaussian) using these responsibilities to maximize the likelihood of the data. This alternation continues until convergence is achieved, ensuring that the final parameters are those that best explain the observed data .
Decision trees offer several advantages, such as interpretability, ease of explanation, and the ability to handle both numerical and categorical data . They are versatile and require minimal preprocessing of data. However, they can be prone to overfitting, especially if not pruned adequately. Compared to more complex models like random forests or neural networks, decision trees might not capture complex relationships as effectively and typically have lower predictive power in practice. Nevertheless, their simplicity and visual appeal make them a popular choice for initial modeling and understanding data-driven decision processes .
The decision criterion, such as Gini impurity or information gain, guides how nodes are split in decision trees. The choice of criterion directly influences which attributes are used at each split, impacting the tree's depth and complexity . A criterion that better captures the variance or information in the data will result in clearer, more effective splits, enhancing predictive accuracy. Poorly chosen criteria can lead to suboptimal trees with high bias or variance, reducing both interpretability and predictive capability .
Continuous attributes in decision trees can lead to complex splitting conditions and potentially deep trees. These attributes require discretization or selection of thresholds for splitting, which can increase computational complexity . The decision tree algorithm addresses this by determining optimal points to split the continuous data using criteria like information gain. Proper handling of continuous attributes is crucial for preventing overfitting and ensuring manageable tree complexity .
In the traditional k-means algorithm, centroids are initialized randomly throughout the data space without any consideration of data distribution, which can lead to suboptimal clustering if centroids are poorly initialized. In contrast, the k-means++ algorithm starts by selecting the first centroid randomly, but subsequent centroids are chosen based on a probability proportional to the squared distance from the nearest existing centroid . This method aims to position initial centroids more strategically and thus often results in better clustering performance .
The stopping criterion in decision tree algorithms, such as maximum depth or minimum instances per leaf, directly impacts model complexity and generalization. A stringent stopping criterion reduces tree depth, potentially underfitting by not capturing sufficient complexity in the data. Conversely, lenient criteria allow deeper trees, possibly capturing noise and leading to overfitting . Therefore, stopping criteria need careful calibration to balance complexity and generalization, ensuring the tree is neither too simplistic nor overly detailed .