Machine Learning With Python
Machine Learning With Python
1. Implement and demonstrate the FIND-S algorithm for finding the most specific
hypothesis based on a given set of training data samples. Read the training data from a .CSV
file.
FIND-S Algorithm
1. Initialize h to the most specific hypothesis in H
2. For each positive training instance x
For each attribute constraint ai in h
Training Examples:
Program:
import csv a =
[]
print("\n The total number of training instances are : ",len(a)) num_attribute = len(a[0])-1
print("\n The Maximally specific hypothesis for the training instance is ")
print(hypothesis)
Data Set:
Output:
instances are : 4
The hypothesis for the training instance 1 is : ['sunny', 'warm', 'normal', 'strong',
'warm', 'same']
The hypothesis for the training instance 2 is : ['sunny', 'warm', '?', 'strong', 'warm',
'same']
The hypothesis for the training instance 3 is : ['sunny', 'warm', '?', 'strong', 'warm',
'same']
2. For a given set of training data examples stored in a .CSV file, implement and demonstrate
the Candidate-Elimination algorithm to output a description of the set of all hypotheses
consistent with the training examples.
• If d is a negative example
• Remove from S any hypothesis inconsistent with d
• For each hypothesis g in G that is not consistent with d
• Remove g from G
• Add to G all minimal specializations h of g such that
• h is consistent with d, and some member of S is more specific than h
• Remove from G any hypothesis that is less general than another hypothesis in G
Training Examples:
Program:
Data Set:
Output:
Final Specific_h:
['sunny' 'warm' '?' 'strong' '?' '?']
Final General_h:
[['sunny', '?', '?', '?', '?', '?'],
['?', 'warm', '?', '?', '?', '?']]
3. Write a program to demonstrate the working of the decision tree based ID3 algorithm. Use
an appropriate data set for building the decision tree and apply this knowledge to classify a
new sample.
ID3 Algorithm
Examples are the training examples. Target_attribute is the attribute whose value is to
be predicted by the tree. Attributes is a list of other attributes that may be tested by the
learned decision tree. Returns a decision tree that correctly classifies the given
Examples.
8. Otherwise Begin
• A ← the attribute from Attributes that best* classifies Examples
• The decision attribute for Root ← A
• For each possible value, vi, of A,
• Add a new tree branch below Root, corresponding to the test A = vi
• Let Examples vi, be the subset of Examples that have value vi for A
• If Examples vi , is empty
• Then below this new branch add a leaf node with label = most common
value of Target_attribute in Examples
• Else below this new branch add the subtree
ID3(Examples vi, Targe_tattribute, Attributes –
{A}))
9. End
10. Return Root
ENTROPY:
Entropy measures the impurity of a collection of examples.
INFORMATION GAIN:
Training Dataset:
Test Dataset:
Program:
import math
import csv
def load_csv(filename):
lines=[Link](open(filename,"r"));
dataset = list(lines) headers =
[Link](0) return
dataset,headers
class Node:
def init (self,attribute): [Link]=attribute
[Link]=[] [Link]=""
def subtables(data,col,delete):
dic={}
coldata=[row[col] for row in data]
attr=list(set(coldata))
counts=[0]*len(attr)
r=len(data) c=len(data[0])
for x in range(len(attr)): for y in
range(r):
if data[y][col]==attr[x]: counts[x]
+=1
for x in range(len(attr)):
dic[attr[x]]=[[0 for i in range(c)] for j in range(counts[x])]
pos=0
for y in range(r):
if data[y][col]==attr[x]: if delete:
del data[y][col] dic[attr[x]]
[pos]=data[y] pos+=1
return attr,dic
def entropy(S):
attr=list(set(S))
if len(attr)==1: return 0
counts=[0,0]
for i in range(2):
counts[i]=sum([1 for x in S if attr[i]==x])/(len(S)*1.0)
sums=0
for cnt in counts:
sums+=-1*cnt*[Link](cnt,2) return sums
def compute_gain(data,col):
attr,dic = subtables(data,col,delete=False)
total_size=len(data)
entropies=[0]*len(attr)
ratio=[0]*len(attr)
def build_tree(data,features):
lastcol=[row[-1] for row in data] if(len(set(lastcol)))==1:
node=Node("")
[Link]=lastcol[0] return
node
n=len(data[0])-1
gains=[0]*n
for col in range(n): gains[col]=compute_gain(data,col)
split=[Link](max(gains))
node=Node(features[split])
fea = features[:split]+features[split+1:] attr,dic=subtables(data,split,delete=True)
def print_tree(node,level):
if [Link]!="":
print(" "*level,[Link]) return
def classify(node,x_test,features):
if [Link]!="":
print([Link]) return
pos=[Link]([Link]) for value, n in
[Link]:
if x_test[pos]==value:
classify(n,x_test,features)
'''Main program'''
dataset,features=load_csv("[Link]") node1=build_tree(dataset,features)
print("The decision tree for the dataset using ID3 algorithm is")
print_tree(node1,0) testdata,features=load_csv("data3_test.csv") for
xtest in testdata:
print("The test instance:",xtest)
print("The label for test instance:",end=" ")
classify(node1,xtest,features)
Output:
Outlook
rain
Wind
strong
no
weak
yes
overcast
yes
sunny
Humidity
normal
yes
high
no
BACKPROPAGATION Algorithm
• Create a feed-forward network with ni inputs, nhidden hidden units, and nout output
units.
• Initialize all network weights to small random numbers
• Until the termination condition is met, Do
1. Input the instance ⃗𝑥 , to the network and compute the output ou of every
Propagate the input forward through the network:
Training Examples:
Expected % in
Example Sleep Study
Exams
1 2 9 92
2 1 5 86
3 3 6 89
Program:
import numpy as np
X = [Link](([2, 9], [1, 5], [3, 6]), dtype=float)
y = [Link](([92], [86], [89]), dtype=float)
X = X/[Link](X,axis=0) # maximum of X array longitudinally y = y/100
#Variable initialization
epoch=5000 #Setting training iterations lr=0.1
#Setting learning rate
inputlayer_neurons = 2 #number of features in data set
hiddenlayer_neurons = 3 #number of hidden layers neurons output_neurons
=1 #number of neurons at output layer
#Forward Propogation
hinp1=[Link](X,wh)
hinp=hinp1 + bh
hlayer_act = sigmoid(hinp)
outinp1=[Link](hlayer_act,wout) outinp= outinp1+
bout
output = sigmoid(outinp)
#Backpropagation EO =
y-output
outgrad = derivatives_sigmoid(output) d_output = EO*
outgrad
EH = d_output.dot(wout.T)
Output:
Input:
[[0.66666667 1. ]
[0.33333333 0.55555556]
[1. 0.66666667]]
Actual Output:
[[0.92]
[0.86]
[0.89]]
Predicted Output:
[[0.89726759]
[0.87196896]
[0.9000671]]
[Link] a program to implement k-Nearest Neighbour algorithm to classify the iris data set.
Print both correct and wrong predictions. Java/Python ML library classes can be used for this
problem.
Training algorithm:
• For each training example (x, f (x)), add the example to the list training
examples Classification algorithm:
• Given a query instance xq to be classified,
• Let x1 . . .xk denote the k instances from training examples that are nearest to xq
• Return
• Where, f(xi) function to calculate the mean value of the k nearest training
examples.
Data Set:
Iris Plants Dataset: Dataset contains 150 instances (50 in each of three classes)
Number of Attributes: 4 numeric, predictive attributes and the Class
Program:
""" Iris Plants Dataset, dataset contains 150 (50 in each of three
classes)Number of Attributes: 4 numeric, predictive attributes and
the Class
"""
iris=datasets.load_iris()
""" The x variable contains the first four columns of the dataset
(i.e. attributes) while y contains the labels.
"""
x = [Link] y =
[Link]
""" Splits the dataset into 70% train data and 30% test data. This
means that out of total 150 records, the training set will contain
105 records and the test set contains 45 of those records
"""
x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.3)
Output:
Confusion Matrix
[[20 0 0]
[ 0 10 0]
[ 0 1 14]]
Accuracy Metrics
Basic knowledge
Confusion Matrix
True positives: data points labelled as positive that are actually positive
False positives: data points labelled as positive that are actually negative
True negatives: data points labelled as negative that are actually negative
False negatives: data points labelled as negative that are actually positive
F1-Score:
Example:
Experiment-4: Exercise to solve the real world problems using the following machine
learning methods:(a) Linear Regression (b) Logistic Regression
(c) Binary classifier
Regression
The term regression is used when you try to find the relationship between variables.
In Machine Learning, and in statistical modeling, that relationship is used to predict the outcome of future events.
Linear Regression
Linear regression uses the relationship between the data-points to draw a straight line through all them.
In the example below, the x-axis represents age, and the y-axis represents speed. We have registered the age and
speed of 13 cars as they were passing a tollbooth. Let us see if the data we collected could be used in a linear
regression:
Example
import sys
import matplotlib
[Link]('Agg')
x = [5,7,8,7,2,17,2,9,4,11,12,9,6]
y = [99,86,87,88,111,86,103,87,94,78,77,85,86]
[Link](x, y)
[Link]()
[Link]([Link])
[Link]()
Result:
Logistic Regression:
Logistic regression aims to solve classification problems. It does this by predicting categorical outcomes, unlike
linear regression that predicts a continuous outcome.
In the simplest case there are two outcomes, which is called binomial, an example of which is predicting if a
tumor is malignant or benign. Other cases have more than two outcomes to classify, in this case it is called
multinomial. A common example for multinomial logistic regression would be predicting the class of an iris
flower between 3 different species.
Here we will be using basic logistic regression to predict a binomial variable. This means it has only two possible
outcomes.
import numpy
#Note: X has to be reshaped into a column from a row for the LogisticRegression() function
to work.
#y represents whether or not the tumor is cancerous (0 for "No", 1 for "Yes").
y = [Link]([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1])
We will use a method from the sklearn module, so we will have to import that module as
well:
From the sklearn module we will use the LogisticRegression() method to create a
logistic regression object.
This object has a method called fit() that takes the independent and dependent values as
parameters and fills the regression object with data that describes the relationship:
logr = linear_model.LogisticRegression()
[Link](X,y)
Now we have a logistic regression object that is ready to whether a tumor is cancerous
based on the tumor size:
Program:
import numpy
X = [Link]([3.78, 2.44, 2.09, 0.14, 1.72, 1.65, 4.92, 4.37, 4.96, 4.52, 3.69, 5.88]).reshape(-1,1)
y = [Link]([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1])
logr = linear_model.LogisticRegression()
[Link](X,y)
predicted = [Link]([Link]([3.46]).reshape(-1,1))
print(predicted)
Result:
[[4.03541657]]
Let’s consider a scenario where you are told to seperate a basket full of Apples and
Oranges into two seperate baskets.
Afer you find the difference between the two, then you’ll seperate them.
Now, let’s explain the Binary Classifier from the above scenario.
1. Firstly, you get the data to solve your problem. (Basket full of Apples and
Oranges)
2. Secondly, you create a feature set, which uniquely defines each data. (Your
assumptions like color, size, weights and etc.)
3. Thirdly, you are able to label or categorize each data. (Apple or Orange)
4. Fourthly, you have learnt to differentiate the data during the entire process. (In
future, you’ll be able to differentiate between an Apple and a Orange)
1. Supervised Learning
2. Unsupervised Learning
3. Reinforcement Learning
1. Data Preprocessing
As Machine Learning algorithms learn from the data, we are obliged to feed them
the right kind of data. So, the step towards achieving that is via Data
Preprocessing.
Data Preprocessing is a data mining technique that involves transforming the raw
data into an understandable format. Real-world data is often incomplete, noisy,
inconsistent or unreliable and above all it might be unstructured.
In simple terms, Data Preprocessing implies grooming the raw data according to
your requirement using certain techniques.
1. Data Cleaning — Fill in the missing values, detect and remove noisy data and
outliers.
2. Data Transformation — Normalize data to reduce dimensions and noise.
3. Data Reduction — Sample data records or attributes for easier data handling.
4. Data Discretization — Convert continuous attributes to categorical attributes
for ease of use with certain machine learning methods.
5. Text Cleaning — Remove embedded characters which may cause data
misalignment, for e.g., embedded tabs in a tab-separated data file, embedded
new lines which may break records, etc.
2. Learning
Once you have your dataset after preprocessing, then it’s time to select a learning
algorithm to perform your desired task. In our case it’s Binary Classifier or a
Perceptron.
1. Accuracy
2. Training Time
3. Linearity
4. Number of Parameters
3. Evaluation
The metrics that you choose to evaluate the machine learning algorithm are very
important. The choice of metrics influences how the performance of machine
learning is measured and compared.
Classification Metrics
1. Classification Accuracy
2. Logarithmic Loss
3. Area Under ROC Curve
4. Confusion Matrix
5. Classification Report
Regression Metrics
Algorithm
Where,
Implementation
1. Let’s initialize an array with initial weights equal to 0. The length of the array is
equal to number of features + 1. The additional feature is the “threshold”.
2. The loop “iterates” multiple times over the training data to optimize the weights
of the dataset.
for _ in range(number_of_iterations):
3. We loop over each training data point and it’s target. The target is the desired
output which we want the algorithm to predict. As it’s a binary classifier, the
targeted ouput is either a 0 or 1.
At each iteration, if the prediction is not accurate, the algorithm will adjust the
weights. The adjustment of the weights will be done proportionally to the
difference between the target and predicted value.
The difference is then mulitplied by the learning rate (rate). Higher the value of rate,
larger the correction of weights. The algorithm will stop to adjust the weights when
the predicted value becomes accurate.
Program:
import numpy as np
class Perceptron(object):
""" Perceptron Classifier
Parameters
------------
rate : float
Learning rate (ranging from 0.0 to 1.0)
number_of_iteration : int
Number of iterations over the input dataset.
Attributes:
------------
weight_matrix : 1d-array
Weights after fitting.
error_matrix : list
Number of misclassification in every epoch(one full training cycle on the training set)
"""
Parameters:
------------
X : array-like, shape = [number_of_samples, number_of_features]
Training vectors.
y : array-like, shape = [number_of_samples]
Target values.
Returns
------------
self : object
"""
for _ in range(self.number_of_iterations):
errors = 0
for xi, target in zip(X, y):
update = [Link] * (target - [Link](xi))
self.weight_matrix[1:] += update * xi
self.weight_matrix[0] += update
errors += int(update != 0.0)
self.errors_list.append(errors)
return self
if __name__ == '__main__':
X = [Link]([[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0]])
y = [Link]([0, 1, 1, 1, 1, 1, 1])
p = Perceptron()
[Link](X, y)
print("Predicting the output of [1, 1, 1] = {}".format([Link]([1, 1, 1])))
Experiment -6:
In many Machine-learning or Data Science activities, the data set might contain text or categorical
values (basically non-numerical values). For example, color feature having values like red, orange, blue,
white etc. Meal plan having values like breakfast, lunch, snacks, dinner, tea etc. Few algorithms such as
CATBOAST, decision-trees can handle categorical values very well but most of the algorithms expect
Over your learning curve in AI and Machine Learning, one thing you would notice that most of the
algorithms work better with numerical inputs. Therefore, the main challenge faced by an analyst is to
convert text/categorical data into numerical data and still make an algorithm/model to make sense out of
it. Neural networks, which is a base of deep-learning, expects input values to be numerical.
There are many ways to convert categorical values into numerical values. Each approach has its own
trade-offs and impact on the feature set. Hereby, I would focus on 2 main methods: One-Hot-Encoding
and Label-Encoder. Both of these encoders are part of SciKit-learn library (one of the most widely used
Python library) and are used to convert text or categorical data into numerical data which the model
Code snippets in this article would be of Python since I am more comfortable with Python. If you need
Label Encoding
This approach is very simple and it involves converting each value in a column to a number. Consider a
dataset of bridges having a column names bridge-types having below values. Though there will be many
more columns in the dataset, to understand label-encoding, we will focus on one categorical column
only.
BRIDGE-TYPE
Arch
Beam
Truss
Cantilever
Tied Arch
Suspension
Cable
We choose to encode the text values by putting a running sequence for each text values like below:
With this, we completed the label-encoding of variable bridge-type. That’s all label encoding is about.
But depending upon the data values and type of data, label encoding induces a new problem since it uses
number sequencing. The problem using the number is that they introduce relation/comparison between
them. Apparently, there is no relation between various bridge type, but when looking at the number, one
might think that ‘Cable’ bridge type has higher precedence over ‘Arch’ bridge type. The algorithm might
misunderstand that data has some kind of hierarchy/order 0 < 1 < 2 … < 6 and might give 6X more
Let’s consider another column named ‘Safety Level’. Performing label encoding of this column also
induces order/precedence in number, but in the right way. Here the numerical order does not look out-of-
box and it makes sense if the algorithm interprets safety order 0 < 1 < 2 < 3 < 4 i.e. none < low <
This approach requires the category column to be of ‘category’ datatype. By default, a non-numerical
column is of ‘object’ type. So you might have to change type to ‘category’ before using this approach.
Another common approach which many data analyst perform label-encoding is by using SciKit learn
library.
import pandas as pd
import numpy as np
from [Link] import LabelEncoder# creating initial dataframe
bridge_types = ('Arch','Beam','Truss','Cantilever','Tied Arch','Suspension','Cable')
bridge_df = [Link](bridge_types, columns=['Bridge_Types'])# creating instance of labelencoder
labelencoder = LabelEncoder()# Assigning numerical values and storing in another column
bridge_df['Bridge_Types_Cat'] = labelencoder.fit_transform(bridge_df['Bridge_Types'])
bridge_df
One-Hot Encoder
Though label encoding is straight but it has the disadvantage that the numeric values can be
misinterpreted by algorithms as having some sort of hierarchy/order in them. This ordering issue is
addressed in another common alternative approach called ‘One-Hot Encoding’. In this strategy, each
category value is converted into a new column and assigned a 1 or 0 (notation for true/false) value to the
column. Let’s consider the previous example of bridge type and safety levels with one-hot encoding.
Above are the one-hot encoded values of categorical column ‘Bridge-Type’. In the same way, let's check
Rows which have the first column value (Arch/None) will have ‘1’ (indicating true) and other value’s
columns will have ‘0’ (indicating false). Similarly, for other rows matching value with column value.
Though this approach eliminates the hierarchy/order issues but does have the downside of adding more
columns to the data set. It can cause the number of columns to expand greatly if you have many unique
values in a category column. In the above example, it was manageable, but it will get really challenging
OneHotEncoder from SciKit library only takes numerical categorical values, hence any value of string
type should be label encoded before one hot encoded. So taking the dataframe from the previous
import pandas as pd
import numpy as np
from [Link] import OneHotEncoder# creating instance of one-hot-encoder
enc = OneHotEncoder(handle_unknown='ignore')# passing bridge-types-cat column (label encoded values of
bridge_types)
enc_df = [Link](enc.fit_transform(bridge_df[['Bridge_Types_Cat']]).toarray())# merge with main df
bridge_df on key values
bridge_df = bridge_df.join(enc_df)
bridge_df
This approach is more flexible because it allows encoding as many category columns as you would like
and choose how to label the columns using a prefix. Proper naming will make the rest of the analysis just
import pandas as pd
import numpy as np# creating initial dataframe
bridge_types = ('Arch','Beam','Truss','Cantilever','Tied Arch','Suspension','Cable')
bridge_df = [Link](bridge_types, columns=['Bridge_Types'])# generate binary values using
get_dummies
dum_df = pd.get_dummies(bridge_df, columns=["Bridge_Types"], prefix=["Type_is"] )# merge with main
df bridge_df on key values
bridge_df = bridge_df.join(dum_df)
bridge_df
Regression:
Regression is a technique from statistics that are used to predict values of the desired target
quantity when the target quantity is continuous.
In regression, we seek to identify (or estimate) a continuous variable y associated with a given
input vector x.
y is called the dependent variable.
x is called the independent variable.
Loess/Lowess Regression:
Loess regression is a nonparametric technique that uses local weighted regression to fit a smooth curve
through points in a scatter plot.
Lowess Algorithm:
Locally weighted regression is a very powerful nonparametric model used in statistical learning.
Given a dataset X, y, we attempt to find a model parameter β(x) that minimizes residual sum of
weighted squared errors.
The weights are given by a kernel function (k or w) which can be chosen arbitrarily
Algorithm
1. Read the Given data Sample to X and the curve (linear or non linear) to Y
6. Prediction = x0*β
import pandas as pd
import numpy as np
m,n = [Link](xmat)
weights = [Link]([Link]((m)))
for j in range(m):
weights[j,j] = [Link](diff*diff.T/(-2.0*k**2))
return weights
wei = kernel(point,xmat,k)
W = (X.T*(wei*X)).I*(X.T*(wei*ymat.T))
return W
m,n = [Link](xmat)
ypred = [Link](m)
for i in range(m):
ypred[i] = xmat[i]*localWeight(xmat[i],xmat,ymat,k)
return ypred
data = pd.read_csv('[Link]')
bill = [Link](data.total_bill)
tip = [Link]([Link])
mbill = [Link](bill)
mtip = [Link](tip)
m= [Link](mbill)[1]
one = [Link]([Link](m))
X = [Link]((one.T,mbill.T))
#set k here
ypred = localWeightRegression(X,mtip,0.5)
SortIndex = X[:,1].argsort(0)
xsort = X[SortIndex][:,0]
fig = [Link]()
ax = fig.add_subplot(1,1,1)
[Link](bill,tip, color='green')
[Link]('Total bill')
[Link]('Tip')
[Link]();
Output
Data set:
Experiment-10 : Assuming a set of documents that need to be classified, use the naïve Bayesian
Classifier model to perform this task. Built-in Java classes/API can be used to write the program.
Calculate the accuracy, precision, and recall for your data set.
Where,
P(h|D) is the probability of hypothesis h given the data D. This is called the posterior probability
P(D|h) is the probability of data d given that the hypothesis h was true.
P(h) is the probability of hypothesis h being true. This is called the prior probability of h. P(D) is the
probability of the data. This is called the prior probability of D
After calculating the posterior probability for a number of different hypotheses h, and is interested in
finding the most probable hypothesis h ∈ H given the observed data D. Any such maximally probable
hypothesis is called a maximum a posteriori (MAP) hypothesis.
Bayes theorem to calculate the posterior probability of each candidate hypothesis is hMAP is a MAP
hypothesis provided.
CLASSIFY_NAIVE_BAYES_TEXT (Doc)
Return the estimated target value for the document Doc. ai denotes the word found in the ith position
within Doc.
positions ← all word positions in Doc that contain tokens found in Vocabulary
Return VNB, where
Data set:
Save dataset in .csv format
Python Program to Implement and Demonstrate Naïve Bayesian Classifier using API for
document classification
"""
6. Assuming a set of documents that need to be classified, use the naïve Bayesian Classifier model to
perform this task.
Built-in Java classes/API can be used to write the program. Calculate the accuracy, precision, and recall
for your data set
"
import pandas as pd
msg=pd.read_csv('[Link]',names=['message','label'])
msg['labelnum']=[Link]({'pos':1,'neg':0})
X=[Link]
y=[Link]
xtrain,xtest,ytrain,ytest=train_test_split(X,y)
cv = CountVectorizer()
xtrain_dtm = cv.fit_transform(xtrain)
xtest_dtm=[Link](xtest)
print(cv.get_feature_names())
df=[Link](xtrain_dtm.toarray(),columns=cv.get_feature_names())
clf = MultinomialNB().fit(xtrain_dtm,ytrain)
predicted = [Link](xtest_dtm)
print(metrics.confusion_matrix(ytest,predicted))
Output
9. He is my sworn enemy
1 1
2 1
3 1
4 1
5 0
6 0
7 0
8 0
9 0
10 1
11 0
12 1
13 0
14 1
15 0
16 1
17 0
The total number of Training Data: (13,) The total number of Test Data: (5,)
[‘about’, ‘am’, ‘amazing’, ‘an’, ‘and’, ‘awesome’, ‘beers’, ‘best’, ‘can’, ‘deal’, ‘do’, ‘enemy’, ‘feel’,
‘fun’, ‘good’, ‘great’, ‘have’, ‘he’, ‘holiday’, ‘house’, ‘is’, ‘like’, ‘love’, ‘my’, ‘not’, ‘of’, ‘place’,
‘restaurant’, ‘sandwich’, ‘sick’, ‘sworn’, ‘these’, ‘this’, ‘tired’, ‘to’, ‘today’, ‘tomorrow’, ‘very’, ‘view’,
‘we’, ‘went’, ‘what’, ‘will’, ‘with’, ‘work’]
Confusion matrix
[[2 1]
[0 2]]
Experiment-11: Apply EM algorithm to cluster a set of data stored in a .CSV file. Use the same
data set for clustering using the k-Means algorithm. Compare the results of these two algorithms and
comment on the quality of clustering. You can add Java/Python ML library classes/API in the program.
import pandas as pd
import numpy as np
X = [Link][:, :-1]
[Link](figsize=(14,7))
colormap=[Link](['red','lime','black'])
# REAL PLOT
[Link](1,3,1)
[Link]('Real')
[Link](X.Petal_Length,X.Petal_Width,c=colormap[y])
# K-PLOT
model=KMeans(n_clusters=3, random_state=0).fit(X)
[Link](1,3,2)
[Link]('KMeans')
[Link](X.Petal_Length,X.Petal_Width,c=colormap[model.labels_])
# GMM PLOT
gmm=GaussianMixture(n_components=3, random_state=0).fit(X)
y_cluster_gmm=[Link](X)
[Link](1,3,3)
[Link]('GMM Classification')
[Link](X.Petal_Length,X.Petal_Width,c=colormap[y_cluster_gmm])
Output
[[ 0 50 0]
[48 0 2]
[14 0 36]]
[[50 0 0]
[ 0 5 45]
[ 0 50 0]]
Data Set:
Iris-
6.1 2.9 4.7 1.4
versicolor
Iris-
5.6 2.9 3.6 1.3
versicolor
Iris-
6.7 3.1 4.4 1.4
versicolor
Iris-
5.6 3 4.5 1.5
versicolor
Iris-
5.8 2.7 4.1 1
versicolor
Iris-
6.2 2.2 4.5 1.5
versicolor
Iris-
5.6 2.5 3.9 1.1
versicolor
Iris-
5.9 3.2 4.8 1.8
versicolor
Iris-
6.1 2.8 4 1.3
versicolor
Iris-
6.3 2.5 4.9 1.5
versicolor
Iris-
6.1 2.8 4.7 1.2
versicolor
Iris-
6.4 2.9 4.3 1.3
versicolor
Iris-
6.6 3 4.4 1.4
versicolor
Iris-
6.8 2.8 4.8 1.4
versicolor
Iris-
6.7 3 5 1.7
versicolor
Iris-
6 2.9 4.5 1.5
versicolor
Iris-
5.7 2.6 3.5 1
versicolor
Iris-
5.5 2.4 3.8 1.1
versicolor
Iris-
5.5 2.4 3.7 1
versicolor
Iris-
5.8 2.7 3.9 1.2
versicolor
Iris-
6 2.7 5.1 1.6
versicolor
Iris-
5.4 3 4.5 1.5
versicolor
Iris-
6 3.4 4.5 1.6
versicolor
Iris-
6.7 3.1 4.7 1.5
versicolor
Iris-
6.3 2.3 4.4 1.3
versicolor
Iris-
5.6 3 4.1 1.3
versicolor
Iris-
5.5 2.5 4 1.3
versicolor
Iris-
5.5 2.6 4.4 1.2
versicolor
Iris-
6.1 3 4.6 1.4
versicolor
Iris-
5.8 2.6 4 1.2
versicolor
Iris-
5 2.3 3.3 1
versicolor
Iris-
5.6 2.7 4.2 1.3
versicolor
Iris-
5.7 3 4.2 1.2
versicolor
Iris-
5.7 2.9 4.2 1.3
versicolor
Iris-
6.2 2.9 4.3 1.3
versicolor
Iris-
5.1 2.5 3 1.1
versicolor
Iris-
5.7 2.8 4.1 1.3
versicolor
Iris-
6.3 3.3 6 2.5
virginica
Iris-
5.8 2.7 5.1 1.9
virginica
Iris-
7.1 3 5.9 2.1
virginica
Iris-
6.3 2.9 5.6 1.8
virginica
Iris-
6.5 3 5.8 2.2
virginica
Iris-
7.6 3 6.6 2.1
virginica
Iris-
4.9 2.5 4.5 1.7
virginica
Iris-
7.3 2.9 6.3 1.8
virginica
Iris-
6.7 2.5 5.8 1.8
virginica
Iris-
7.2 3.6 6.1 2.5
virginica
Iris-
6.5 3.2 5.1 2
virginica
Iris-
6.4 2.7 5.3 1.9
virginica
Iris-
6.8 3 5.5 2.1
virginica
Iris-
5.7 2.5 5 2
virginica
Iris-
5.8 2.8 5.1 2.4
virginica
Iris-
6.4 3.2 5.3 2.3
virginica
Iris-
6.5 3 5.5 1.8
virginica
Iris-
7.7 3.8 6.7 2.2
virginica
Iris-
7.7 2.6 6.9 2.3
virginica
Iris-
6 2.2 5 1.5
virginica
Iris-
6.9 3.2 5.7 2.3
virginica
Iris-
5.6 2.8 4.9 2
virginica
Iris-
7.7 2.8 6.7 2
virginica
Iris-
6.3 2.7 4.9 1.8
virginica
Iris-
6.7 3.3 5.7 2.1
virginica
Iris-
7.2 3.2 6 1.8
virginica
Iris-
6.2 2.8 4.8 1.8
virginica
Iris-
6.1 3 4.9 1.8
virginica
Iris-
6.4 2.8 5.6 2.1
virginica
Iris-
7.2 3 5.8 1.6
virginica
Iris-
7.4 2.8 6.1 1.9
virginica
Iris-
7.9 3.8 6.4 2
virginica
Iris-
6.4 2.8 5.6 2.2
virginica
Iris-
6.3 2.8 5.1 1.5
virginica
Iris-
6.1 2.6 5.6 1.4
virginica
Iris-
7.7 3 6.1 2.3
virginica
Iris-
6.3 3.4 5.6 2.4
virginica
Iris-
6.4 3.1 5.5 1.8
virginica
Iris-
6 3 4.8 1.8
virginica
Iris-
6.9 3.1 5.4 2.1
virginica
Iris-
6.7 3.1 5.6 2.4
virginica
Iris-
6.9 3.1 5.1 2.3
virginica
Iris-
5.8 2.7 5.1 1.9
virginica
Iris-
6.8 3.2 5.9 2.3
virginica
Iris-
6.7 3.3 5.7 2.5
virginica
Iris-
6.7 3 5.2 2.3
virginica
Iris-
6.3 2.5 5 1.9
virginica
Iris-
6.5 3 5.2 2
virginica
Iris-
6.2 3.4 5.4 2.3
virginica
Iris-
5.9 3 5.1 1.8
virginica
Introduction to EDA
The main objective of this article is to cover the steps involved in Data pre-processing,
Feature Engineering, and different stages of Exploratory Data Analysis, which is an
essential step in any research analysis.
Data pre-processing, Feature Engineering, and EDA are fundamental early steps after data
collection. Still, they are not limited to where the data is simply visualized, plotted, and
manipulated, without any assumptions, to assess the quality of the data and building models.
Transform into an expert and significantly impact the world of data science.
Download Brochure
Data Pre-processing refers to Data Integration, Data Analysis, Data cleaning, Data
Transformation, and Dimension Reduction
Data preprocessing is the process of cleaning and preparing the raw data to enable
feature engineering
Feature Engineering is one of the most crucial tasks and plays a major role in determining
the outcome of a model
The Data pre-processing, Feature Engineering, and EDA steps will be carried out in this
article using Python.
Import all libraries which are required for our analysis, such as Data Loading, Statistical
analysis, Visualizations, Data Transformations, Merge and Joins, etc.
Pandas and Numpy have been used for Data Manipulation and numerical Calculations
import pandas as pd
import numpy as np
import [Link] as plt
import seaborn as sns
#to ignore warnings
import warnings
[Link]('ignore')
Reading Dataset
The Pandas library offers a wide range of possibilities for loading data into the pandas
DataFrame from files like JSON, .csv, .xlsx, .sql, .pickle, .html, .txt, images etc.
Most of the data are available in a tabular format of CSV files. It is trendy and easy to
access. Using the read_csv() function, data can be converted to a pandas DataFrame.
In this article, the data to predict Used car price is being used as an example. In this
dataset, we are trying to analyze the used car’s price and how EDA focuses on identifying
the factors influencing the car price. We have stored the data in the DataFrame data.
data = pd.read_csv("used_cars.csv")
Before we make any inferences, we listen to our data by examining all variables in the data.
The main goal of data understanding is to gain general insights about the data, which covers
the number of rows and columns, values in the data, datatypes, and Missing values in the
dataset.
shape – shape will display the number of observations(rows) and features(columns) in the
dataset
[Link]()
[Link]()
info() helps to understand the data type and information about data, including the number of
records in each column, data having null or not null, Data type, the memory usage of the
dataset
[Link]()
[Link]() shows the variables Mileage, Engine, Power, Seats, New_Price, and Price have
missing values. Numeric variables like Mileage, Power are of datatype as float64 and int64.
Categorical variables like Location, Fuel_Type, Transmission, and Owner Type are of
object data type
nunique() based on several unique values in each column and the data description, we can
identify the continuous and categorical columns in the data. Duplicated data can be handled
or removed based on further analysis
[Link]()
isnull() is widely been in all pre-processing steps to identify null values in the data
In our example, [Link]().sum() is used to get the number of missing records in each
column
[Link]().sum()
The below code helps to calculate the percentage of missing values in each column
([Link]().sum()/(len(data)))*100
The percentage of missing values for the columns New_Price and Price is ~86% and ~17%,
respectively.
Data Reduction
Some columns or variables can be dropped if they do not add value to our analysis.
In our dataset, the column [Link] have only ID values, assuming they don’t have any
predictive power to predict the dependent variable.
We start our Feature Engineering as we need to add some columns required for analysis.
Feature Engineering
Feature engineering refers to the process of using domain knowledge to select and transform
the most relevant variables from raw data when creating a predictive model using machine
learning or statistical modeling. The main goal of Feature engineering is to create
meaningful data from raw data.
Creating Features
We will play around with the variables Year and Name in our dataset. If we see the sample
data, the column “Year” shows the manufacturing year of the car.
It would be difficult to find the car’s age if it is in year format as the Age of the car is a
contributing factor to Car Price.
Since car names will not be great predictors of the price in our current data. But we can
process this column to extract important information using brand and Model names. Let’s
split the name and introduce new variables “Brand” and “Model”
data['Brand'] = [Link]().[Link](0)
data['Model'] = [Link]().[Link](1) + [Link]().[Link](2)
data[['Name','Brand','Model']]
Data Cleaning/Wrangling
Some names of the variables are not relevant and not easy to understand. Some data may
have data entry errors, and some variables may need data type conversion. We need to fix
this issue in the data.
In the example, The brand name ‘Isuzu’ ‘ISUZU’ and ‘Mini’ and ‘Land’ looks incorrect. This needs to be
corrected
print([Link]())
print([Link]())
We have done the fundamental data analysis, Featuring, and data clean-up. Let’s move to
the EDA process
Exploratory Data Analysis refers to the crucial process of performing initial investigations
on data to discover patterns to check assumptions with the help of summary statistics and
graphical representations.
EDA can be leveraged to check for outliers, patterns, and trends in the given data.
EDA helps to find meaningful patterns in data.
EDA provides in-depth insights into the data sets to solve our business problems.
EDA gives a clue to impute missing values in the dataset
Statistics Summary
The information gives a quick and simple description of the data.
Can include Count, Mean, Standard Deviation, median, mode, minimum value, maximum
value, range, standard deviation, etc.
Statistics summary gives a high-level idea to identify whether the data has any outliers, data
entry error, distribution of data such as the data is normally distributed or left/right skewed
[Link]().T
Years range from 1996- 2019 and has a high in a range which shows used cars contain both
latest models and old model cars.
On average of Kilometers-driven in Used cars are ~58k KM. The range shows a huge
difference between min and max as max values show 650000 KM shows the evidence of an
outlier. This record can be removed.
Min value of Mileage shows 0 cars won’t be sold with 0 mileage. This sounds like a data
entry issue.
It looks like Engine and Power have outliers, and the data is right-skewed.
The average number of seats in a car is 5. car seat is an important feature in price
contribution.
The max price of a used car is 160k which is quite weird, such a high price for used cars.
There may be an outlier or data entry issue.
describe(include=’all’) provides a statistics summary of all data, include object, category etc
[Link](include='all').T
Before we do EDA, lets separate Numerical and categorical variables for easy analysis
cat_cols=data.select_dtypes(include=['object']).columns
num_cols = data.select_dtypes(include=[Link]).[Link]()
print("Categorical Variables:")
print(cat_cols)
print("Numerical Variables:")
print(num_cols)
Data visualization is essential; we must decide what charts to plot to better understand the
data. In this article, we visualize our data using Matplotlib and Seaborn libraries.
Matplotlib is a Python 2D plotting library used to draw basic charts we use Matplotlib.
Seaborn is also a python library built on top of Matplotlib that uses short lines of code to
create and style statistical plots from Pandas and Numpy
Univariate analysis can be done for both Categorical and Numerical variables.
Categorical variables can be visualized using a Count plot, Bar Chart, Pie Plot, etc.
Numerical Variables can be visualized using Histogram, Box Plot, Density Plot, etc.
In our example, we have done a Univariate analysis using Histogram and Box Plot for
continuous Variables.
In the below fig, a histogram and box plot is used to show the pattern of the variables, as
some variables have skewness and outliers.
Price and Kilometers Driven are right skewed for this data to be transformed, and all
outliers will be handled during imputation
categorical variables are being visualized using a count plot. Categorical variables provide
the pattern of factors influencing car price
Mumbai has the highest number of cars available for purchase, followed by Hyderabad and Coimbatore
~53% of cars have fuel type as Diesel this shows diesel cars provide higher performance
~72% of cars have manual transmission
~82 % of cars are First owned cars. This shows most of the buyers prefer to purchase first-
owner cars
~20% of cars belong to the brand Maruti followed by 19% of cars belonging to Hyundai
WagonR ranks first among all models which are available for purchase
Data Transformation
Before we proceed to Bi-variate Analysis, Univariate analysis demonstrated the data pattern
as some variables to be transformed.
Price and Kilometer-Driven variables are highly skewed and on a larger scale. Let’s do log
transformation.
Log transformation can help in normalization, so this variable can maintain standard scale
with other variables:
For Numerical variables, Pair plots and Scatter plots are widely been used to do Bivariate
Analysis.
A Stacked bar chart can be used for categorical variables if the output variable is a
classifier. Bar plots can be used if the output variable is continuous
In our example, a pair plot has been used to show the relationship between two Categorical
variables.
[Link](figsize=(13,17))
[Link](data=[Link](['Kilometers_Driven','Price'],axis=1))
[Link]()
sights:
The variable Year has a positive correlation with price and mileage
A year has a Negative correlation with kilometers-Driven
Mileage is negatively correlated with Power
As power increases, mileage decreases
Car with recent make is higher at prices. As the age of the car increases price decreases
Engine and Power increase, and the price of the car increases
A bar plot can be used to show the relationship between Categorical variables and
continuous variables
Observations
The price of cars is high in Coimbatore and less price in Kolkata and Jaipur
Automatic cars have more price than manual cars.
Diesel and Electric cars have almost the same price, which is maximum, and LPG cars have
the lowest price
First-owner cars are higher in price, followed by a second
The third owner’s price is lesser than the Fourth and above
Lamborghini brand is the highest in price
Gallardocoupe Model is the highest in price
2 Seater has the highest price followed by 7 Seater
The latest model cars are high in price
Heat Map gives the correlation between the variables, whether it has a positive or negative
correlation.
In our example heat map shows the correlation between the variables.
[Link](figsize=(12, 7))
[Link]([Link](['Kilometers_Driven','Price'],axis=1).corr(), annot = True, vmin = -1, vmax = 1)
[Link]()
We cannot impute the data with a simple Mean/Median. We must need business knowledge
or common insights about the data. If we have domain knowledge, it will add value to the
imputation. Some data can be imputed on assumptions.
In our dataset, we have found there are missing values for many columns like Mileage,
Power, and Seats.
We observed earlier some observations have zero Mileage. This looks like a data entry
issue. We could fix this by filling null values with zero and then the mean value of Mileage
since Mean and Median values are nearly the same for this variable chosen Mean to impute
the values.
[Link][data["Mileage"]==0.0,'Mileage']=[Link]
[Link]().sum()
data['Mileage'].fillna(value=[Link](data['Mileage']),inplace=True)
Similarly, imputation for Seats. As we mentioned earlier, we need to know common insights
about the data.
Let’s assume some cars brand and Models have features like Engine, Mileage, Power, and
Number of seats that are nearly the same. Let’s impute those missing values with the
existing data:
[Link]().sum()
data['Seats'].fillna(value=[Link],inplace=True)
data['Seats']=[Link](['Model','Brand'])['Seats'].apply(lambda x:[Link]([Link]()))
data['Engine']=[Link](['Brand','Model'])['Engine'].apply(lambda x:[Link]([Link]()))
data['Power']=[Link](['Brand','Model'])['Power'].apply(lambda x:[Link]([Link]()))
In general, there are no defined or perfect rules for imputing missing values in a dataset.
Each method can perform better for some datasets but may perform even worse. Only
practice and experiments give the knowledge which works better.
Conclusion
In this article, we tried to analyze the factors influencing the used car’s price.
Through EDA, we got useful insights, and below are the factors influencing the price
of the car and a few takeaways
Most of the customers prefer 2 Seat cars hence the price of the 2-seat cars is higher than
other cars.
The price of the car decreases as the Age of the car increases.
Customers prefer to purchase the First owner rather than the Second or Third.
Due to increased Fuel price, the customer prefers to purchase an Electric vehicle.
Automatic Transmission is easier than Manual.
This way, we perform EDA on the datasets to explore the data and extract all possible
insights, which can help in model building and better decision making.
However, this was only an overview of how EDA works; you can go deeper into it and
attempt the stages on larger datasets.
If the EDA process is clear and precise, our model will work better and gives higher
accuracy!
Experiment -13: Write a python to construct a Bayesian network considering medical [Link]
this model to demonstract the diagnosis of heart patients using standard heart disease Data Set.
Theory
A Bayesian network is a directed acyclic graph in which each edge corresponds to a conditional
dependency, and each node corresponds to a unique random variable.
Bayesian network consists of two major parts: a directed acyclic graph and a set of conditional
probability distributions
For illustration, consider the following example. Suppose we attempt to turn on our computer, but the
computer does not start (observation/evidence). We would like to know which of the possible causes of
computer failure is more likely. In this simplified illustration, we assume only two possible causes of
this misfortune: electricity failure and computer malfunction.
The goal is to calculate the posterior conditional probability distribution of each of the possible
unobserved causes given the observed evidence, i.e. P [Cause | Evidence].
Data Set:
The Cleveland database contains 76 attributes, but all published experiments refer to using a subset of
14 of them. In particular, the Cleveland database is the only one that has been used by ML researchers
to this date. The “Heartdisease” field refers to the presence of heart disease in the patient. It is integer
valued from 0 (no presence) to 4.
Database: 0 1 2 3 4 Total
Attribute Information:
Python Program to Implement and Demonstrate Bayesian network using pgmpy Machine
Learning
import numpy as np
import pandas as pd
import csv
heartDisease = pd.read_csv('[Link]')
heartDisease = [Link]('?',[Link])
print([Link]())
print([Link])
model= BayesianModel([('age','heartdisease'),('sex','heartdisease'),('exang','heartdisease'),
('cp','heartdisease'),('heartdisease','restecg'),('heartdisease','chol')])
[Link](heartDisease,estimator=MaximumLikelihoodEstimator)
HeartDiseasetest_infer = VariableElimination(model)
q1=HeartDiseasetest_infer.query(variables=['heartdisease'],evidence={'restecg':1})
print(q1)
q2=HeartDiseasetest_infer.query(variables=['heartdisease'],evidence={'cp':2})
print(q2)
Output
Introduction
A Support Vector Machine (SVM) is a very powerful and versatile Machine Learning
model, capable of performing linear or nonlinear classification, regression, and even outlier
detection. With this tutorial, we learn about the support vector machine technique and how
to use it in scikit-learn. We will also discover the Principal Component Analysis and its
implementation with scikit-learn.
There are numerous hyper-planes from which to choose to split the two kinds of data points.
Our goal is to discover a plane with the greatest margin, or the greatest distance between
data points from both classes. Maximizing the margin distance adds some reinforcement,
making it easier to classify future data points.
plane when the number of input features reaches three. When the number of features
exceeds three, it becomes impossible to imagine.
Transform into an expert and significantly impact the world of data science.
Download Brochure
Support vectors are data points that are closer to the hyperplane and have an influence on
the hyperplane’s position and orientation. We increase the classifier’s margin by using these
support vectors. The hyperplane’s position will be altered if the support vectors are deleted.
These are the points that will assist us in constructing our SVM.
import pandas as pd
import numpy as np
import [Link] as plt
import seaborn as sns
%matplotlib inline
sns.set_style('whitegrid')
Python Code:
print(cancer.target_names)
[Link]()
[Link]()
[Link](df, hue='target', vars=['mean radius', 'mean texture', 'mean perimeter', 'mean area',
'mean smoothness', 'mean compactness', 'mean concavity',
'mean concave points', 'mean symmetry', 'mean fractal dimension'])
[Link](figsize=(10, 8))
[Link](x = 'mean area', y = 'mean smoothness', hue = 'target', data = df)
print("_______________________________________________")
print(f"CLASSIFICATION REPORT:n{clf_report}")
print("_______________________________________________")
print(f"Confusion Matrix: n {confusion_matrix(y_train, pred)}n")
elif train==False:
pred = [Link](X_test)
clf_report = [Link](classification_report(y_test, pred, output_dict=True))
print("Test Result:n================================================")
print(f"Accuracy Score: {accuracy_score(y_test, pred) * 100:.2f}%")
print("_______________________________________________")
print(f"CLASSIFICATION REPORT:n{clf_report}")
print("_______________________________________________")
print(f"Confusion Matrix: n {confusion_matrix(y_test, pred)}n")
C parameter: Controls trade-off between classifying training points correctly and having a
smooth decision boundary.
Small C (loose) makes the cost (penalty) of misclassification low (soft margin)
Large C (strict) makes the cost of misclassification high (hard margin), forcing the model to
explain input data stricter and potentially over its
gamma parameter: Controls how far the influence of a single training set reaches.
Large gamma: close reach (closer data points have high weight)
Small gamma: far reach (more generalized solution)
degree parameter: Degree of the polynomial kernel function (‘poly’). Ignored by all other
kernels.
Grid search is a popular way to find the right hyper-parameter values. Performing a large
grid search first, then a refined grid search centred on the best results is frequently faster.
Knowing what each hyper-parameter does can also help you identify the right part of the
hyper-parameter space to search for.
[Link](X_train, y_train)
print_score(model, X_train, y_train, X_test, y_test, train=True)
print_score(model, X_train, y_train, X_test, y_test, train=False)
Just like the polynomial features method, the similarity features can be useful with any
Other kernels are available, but they are used far less frequently. Some kernels, for example,
are specialized to particular data structures. When identifying text documents based on
DNA sequences, string kernels are sometimes used.
How do you determine which kernel to use when there are so many options? If the training
set is big or has a lot of characteristics, you should always attempt the linear kernel first.
You should also try the Gaussian RBF kernel if the training set isn’t too big.
svm_clf.fit(X_train, y_train)
print_score(svm_clf, X_train, y_train, X_test, y_test, train=True)
print_score(svm_clf, X_train, y_train, X_test, y_test, train=False)
Singular Value Decomposition is used to reduce the data’s dimensionality and project it to a
lower-dimensional environment.
Unsupervised Machine Learning
A transformation of your data and attempts to find out what features explain the most
variance in your data. For example:
robpca
[Link]()
PCA Visualization
Because it’s difficult to represent high-dimensional data using a single scatter-plot, we may
use PCA to determine the first two main components and visualize the data in this new,
two-dimensional space. However, we must first scale our data to ensure that each feature
has single unit variance.
scaler = StandardScaler()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
X_train = scaler.fit_transform(X_train)
X_test = [Link](X_test)
PCA in Scikit Learn works in a similar way to the other preprocessing methods in Scikit
Learn. We create a PCA object, use the fit method to discover the principle components,
and then use transform to rotate and reduce the dimensionality.
When building the PCA object, we can additionally indicate how many components we
wish to create.
Using these two components we can easily separate these two classes.
All principal components are chosen to describe most of the available variance in
the variable, and all principal components are orthogonal to each other. In all the
sets of the principal component first principal component will always have the
maximum variance.
Principal Axis Method: Principal Component Analysis searches for the linear
combination of the variable for extracting maximum variance from the variables.
Once the PCA is done with the process, it will move forward to another linear
combination which will explain the maximum ratio of the remaining variance,
which would lead to orthogonal factors of the sets. This method is used for
analysing total variance in the variables of the set.
Eigen Vector: It is a nonzero vector that remains parallel after multiplying the
matrix. Suppose 'V' is an eigen vector of dimension R of matrix K with dimension R
* R. If KV and V are parallel. Then the user has to solve KV = PV where both V and
P are unknown for solving eigen vector and eigen value.
Eigen Value: It is also known as "characteristic roots" in PCA. This is used for
measuring the variance in all the variables of the set, which is reported for by that
factor. The proportion of eigen value is the ratio of descriptive importance of the
factors concerning the variables. If the factor is low, then it subsidises less to the
description of variables.
First, we will import the dataset and distribute it into X and Y components for data
analysis.
1. DS = pnd.read_csv('[Link]')
2.
3. # Now, we will distribute the dataset into two components "X" and "Y"
4.
5. X = [Link][: , 0:13].values
6. Y = [Link][: , 13].values
Step 3: In this step, we will split the dataset into the training set and testing set.
In this step, we will do the re-processing on the training and testing set, for
example, fitting the standard scale.
We will apply the PCA function into the training set and testing set for analysis.
Step 6: Now, we will fit Logistic Regression for the training set
Output:
LogisticRegression(random_state=0)
1. Y_pred = classifier_1.predict(X_test)
Output:
Step 10: At last, we will visualize the result of the testing set.
16.
17. for s, t in enumerate([Link](Y_set)):
18. [Link](X_set[Y_set == t, 0], X_set[Y_set == t, 1],
19. c = LCM(('red', 'green', 'blue'))(s), label = t)
20.
21. # title for scatter plot
22. [Link]('Logistic Regression for Testing set')
23. [Link] ('PC_1') # for X_label
24. [Link] ('PC_2') # for Y_label
25. [Link]()
26.
27. # show scatter plot
28. [Link]()
Output: