







































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!








































(NAAC Accredited and An ISO 9001:2015 Certified Institution) (Affiliated to Visvesvaraya Technological University Belgaum and approved by AICTE, New Delhi) NAVARATHNA AGRAHARA, SADAHALLI POST, BANGALORE- 562 110, Tel: 080-3252 9939, 3252 957
CONTENTS
Sl.no. Experiments Page No.
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.
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.
Write a program to demonstrate the working of the decision tree based ID algorithm. Use an appropriate data set for building the decision tree and apply this knowledge to classify a new sample.
4 Build an Artificial Neural Network by implementing the and test the same using appropriate data sets. Backpropagation algorithm 16
5
Write a program to implement the naïve Bayesian classifier for a sample training data set stored as a .CSV file. Compute the accuracy of the classifier, considering few test data sets.
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.
Write a program to construct a Bayesian network considering medical data. Use this model to demonstrate the diagnosis of heart patients using standard Heart Disease Data Set. You can use Java/Python ML library classes/API.
Apply EM algorithm to cluster a set of data stored in a .CSV file. Use the same data set for clustering using 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.
Write 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.
10 Implement the non data points. Select appropriate data set for your experiment and draw graphs.-parametric^ Locally Weighted Regression algorithm^ in order to fit 42
Machine Learning Applications
In classification, inputs are divided into two or more classes, and the learner must produce a model that assigns unseen inputs to one or more (multi-label classification) of these classes. This is typically tackled in a supervised manner. Spam filtering is an example of classification, where the inputs are email (or other) messages and the classes are "spam" and "not spam".
In regression, also a supervised problem, the outputs are continuous rather than discrete. In clustering, a set of inputs is to be divided into groups. Unlike in classification, the groups are not known beforehand, making this typically an unsupervised task.
Density estimation finds the distribution of inputs in some space.
Dimensionality reduction simplifies inputs by mapping them into a lower dimensional space. Topic modeling is a related problem, where a program is given a list of human language documents and is tasked with finding out which documents cover similar topics.
Machine learning Approaches
1. Decision tree learning Decision tree learning uses a decision tree as a predictive model, which maps observations about an item to conclusions about the item's target value.
2. Association rule learning Association rule learning is a method for discovering interesting relations between variables in large databases.
3. Artificial neural networks An artificial neural network (ANN) learning algorithm, usually called "neural network" (NN), is a learning algorithm that is vaguely inspired by biological neural networks. Computations are structured in terms of an interconnected group of artificial neurons, processing information using a connectionist approach to computation. Modern neural networks are non-linear statistical data modeling tools. They are usually used to model complex relationships between inputs and outputs, to find patterns in data, or to capture the statistical structure in an unknown joint probability distribution between observed variables.
4. Deep learning Falling hardware prices and the development of GPUs for personal use in the last few years have contributed to the development of the concept of deep learning which consists of multiple hidden layers in an artificial neural network. This approach tries to model the way the human brain processes light and sound into vision and hearing. Some successful applications of deep learning are computer vision and speech Recognition. 5. Inductive logic programming Inductive logic programming (ILP) is an approach to rule learning using logic Programming as a uniform representation for input examples, background knowledge, and hypotheses. Given an encoding of the known background knowledge and a set of examples represented as a logical database of facts, an ILP system will derive a hypothesized logic program that entails all positive and no negative examples. Inductive programming is a related field that considers any kind of programming languages for representing hypotheses (and not only logic programming), such as functional programs. 6. Support vector machines Support vector machines (SVMs) are a set of related supervised learning methods used for classification and regression. Given a set of training examples, each marked as belonging to one
11. Genetic algorithms A genetic algorithm (GA) is a search heuristic that mimics the process of natural selection, and uses methods such as mutation and crossover to generate new genotype in the hope of finding good solutions to a given problem. In machine learning, genetic algorithms found some uses in the 1980s and 1990s. Conversely, machine learning techniques have been used to improve the performance of genetic and evolutionary algorithms. 12. Rule-based machine learning Rule-based machine learning is a general term for any machine learning method that identifies, learns, or evolves "rules" to store, manipulate or apply, knowledge. The defining characteristic of a rule- based machine learner is the identification and utilization of a set of relational rules that collectively represent the knowledge captured by the system. This is in contrast to other machine learners that commonly identify a singular model that can be universally applied to any instance in order to make a prediction. Rule-based machine learning approaches include learning classifier systems, association rule learning, and artificial immune systems. 13. Feature selection approach Feature selection is the process of selecting an optimal subset of relevant features for use in model construction. It is assumed the data contains some features that are either redundant or irrelevant, and can thus be removed to reduce calculation cost without incurring much loss of information. Common optimality criteria include accuracy, similarity and information measures.
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 :
import random import csv
def read_data(filename): with open(filename, 'r') as csvfile: datareader = csv.reader(csvfile, delimiter=',') traindata = [] for row in datareader: traindata.append(row) return (traindata)
h=['phi','phi','phi','phi','phi','phi' data=read_data('finds.csv') def isConsistent(h,d): if len(h)!=len(d)-1: print('Number of attributes are not same in hypothesis.') return False else: matched= for i in range(len(h)): if ( (h[i]==d[i]) | (h[i]=='any') ): matched=matched+ if matched==len(h): return True else: return False def makeConsistent(h,d): for i in range(len(h)): if((h[i] == 'phi')): h[i]=d[i] elif(h[i]!=d[i]): h[i]='any' return h print('Begin : Hypothesis :',h)
filename = "finds.csv" dataset = loadCsv(filename) print(dataset) hypothesis=['0'] * num_attributes print("Intial Hypothesis") print(hypothesis) print("The Hypothesis are") for i in range(len(dataset)): target = dataset[i][-1] if(target == 'Yes'): for j in range(num_attributes): if(hypothesis[j]=='0'): hypothesis[j] = dataset[i][j] if(hypothesis[j]!= dataset[i][j]): hypothesis[j]='?' print(i+1,'=',hypothesis) print("Final Hypothesis") print(hypothesis)
Output: Attributes = ['Sky', 'Temp', 'Humidity', 'Wind', 'Water', 'Forecast'] [['sky', 'Airtemp', 'Humidity', 'Wind', 'Water', 'Forecast', 'WaterSport'], ['Cloudy', 'Cold', 'High', 'Strong', 'Warm', 'Change', 'Yes'], ['Sunny', 'Warm', 'Normal', 'Strong', 'Warm', 'Same', 'Yes'], ['Sunny', 'Warm', 'High', 'Strong', 'Warm', 'Same', 'Yes'], ['Cloudy', 'Cold', 'High', 'Strong', 'Warm', 'Change', 'No'], ['Sunny', 'Warm', 'High', 'Strong', 'Cool', 'Change', 'Yes'], ['Rain', 'Mild', 'High', 'Weak', 'Cool', 'Change', 'No'], ['Rain', 'Cool', 'Normal', 'Weak', 'Cool', 'Same', 'No'], ['Overcast', 'Cool', 'Normal', 'Strong', 'Warm', 'Same', 'Yes']] Intial Hypothesis ['0', '0', '0', '0', '0', '0'] The Hypothesis are 2 = ['Cloudy', 'Cold', 'High', 'Strong', 'Warm', 'Change'] 3 = ['?', '?', '?', 'Strong', 'Warm', '?'] 4 = ['?', '?', '?', 'Strong', 'Warm', '?'] 6 = ['?', '?', '?', 'Strong', '?', '?'] 9 = ['?', '?', '?', 'Strong', '?', '?'] Final Hypothesis ['?', '?', '?', 'Strong', '?', '?']
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.
Candidate-Elimination Algorithm:
Case 2: If d is a negative example Remove from S any hypothesis that is inconsistent with d For each hypothesis g in G that is not consistent with d
import numpy as np import pandas as pd
data = pd.DataFrame(data=pd.read_csv('finds1.csv')) concepts = np.array(data.iloc[:,0:-1])
target = np.array(data.iloc[:,-1]) def learn(concepts, target): specific_h = concepts[0].copy() print("initialization of specific_h and general_h") print(specific_h) general_h = [["?" for i in range(len(specific_h))] for i in range(len(specific_h))] print(general_h) for i, h in enumerate(concepts): if target[i] == "Yes": for x in range(len(specific_h)): if h[x] != specific_h[x]: specific_h[x] = '?'
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.
High
import numpy as np import math from data_loader import read_data class Node: def init(self, attribute): self.attribute = attribute self.children = [] self.answer = "" def str(self): return self.attribute
def subtables(data, col, delete): dict = {} items = np.unique(data[:, col]) count = np.zeros((items.shape[0], 1), dtype=np.int32) for x in range(items.shape[0]): for y in range(data.shape[0]): if data[y, col] == items[x]: count[x] += 1 for x in range(items.shape[0]): dict[items[x]] = np.empty((int(count[x]), data.shape[1]), dtype="|S32") pos = 0 for y in range(data.shape[0]): if data[y, col] == items[x]: dict[items[x]][pos] = data[y] if delete:^ pos += 1 dict[items[x]] = np.delete(dict[items[x]], col, 1) return items, dict def entropy(S): items = np.unique(S)
if items.size == 1: return 0 counts = np.zeros((items.shape[0], 1)) sums = 0 for x in range(items.shape[0]): counts[x] = sum(S == items[x]) / (S.size * 1.0) for count in counts: sums += -1 * count * math.log(count, 2) return sums def gain_ratio(data, col): items, dict = subtables(data, col, delete=False)
total_size = data.shape[0] entropies = np.zeros((items.shape[0], 1)) intrinsic = np.zeros((items.shape[0], 1)) for x in range(items.shape[0]): ratio = dict[items[x]].shape[0]/(total_size * 1.0) entropies[x] = ratio * entropy(dict[items[x]][:, -1]) intrinsic[x] = ratio * math.log(ratio, 2)
wind b'strong' b'weak'^ b'no' sunny^ b'yes' humidity b'high' b'normal'^ b'no' b'yes'
OR import pandas as pd import numpy as np dataset= pd.read_csv('playtennis.csv',names=['outlook','temperature','humidity','wind','class',]) def entropy(target_col): elements,counts = np.unique(target_col,return_counts = True) entropy = np.sum([(-counts[i]/np.sum(counts))np.log2(counts[i]/np.sum(counts)) for i in range(len(elements))]) return entropy def InfoGain(data,split_attribute_name,target_name="class"): total_entropy = entropy(data[target_name]) vals,counts= np.unique(data[split_attribute_name],return_counts=True) Weighted_Entropy = np.sum([(counts[i]/np.sum(counts))entropy(data.where(data[split_attribute_name]==vals[i]).dropna()[target_name]) for i in range(len(vals))]) Information_Gain = total_entropy - Weighted_Entropy return Information_Gain
def ID3(data,originaldata,features,target_attribute_name="class",parent_node_class = None): if len(np.unique(data[target_attribute_name])) <= 1:
elif len(data)==0:^ return np.unique(data[target_attribute_name])[0] np.unique(originaldata[target_attribute_name])[np.argmax(np.unique(originaldata[target_attribut^ return e_name],return_counts=True)[1])] elif len(features) ==0:
else:^ return parent_node_class np.unique(data[target_attribute_name])[np.argmax(np.unique(data[target_attribute_name],return^ parent_node_class^ = _counts=True)[1])] item_values = [InfoGain(data,feature,target_attribute_name) for feature in features] #Return the information gain values for the features in the dataset best_feature_index = np.argmax(item_values) best_feature = features[best_feature_index] tree = {best_feature:{}} features = [i for i in features if i != best_feature] for value in np.unique(data[best_feature]): value = value sub_data = data.where(data[best_feature] == value).dropna() subtree = ID3(sub_data,dataset,features,target_attribute_name,parent_node_class) tree[best_feature][value] = subtree return(tree) tree = ID3(dataset,dataset,dataset.columns[:-1]) print(' \nDisplay Tree\n',tree)
OUTPUT: Display Tree {'outlook': {'Overcast': 'Yes', 'Rain': {'wind': {'Strong': 'No', 'Weak': 'Yes'}}, 'Sunny': {'humidity': {'High': 'No', 'Normal': 'Yes'}}}}
4. Build an Artificial Neural Network by implementing the Back propagation Algorithm and test the same using appropriate data sets.
Back propagation Algorithm: 1.Load data set
// Propagate the errors backward through the network for every node in the output layer calculate the error signal end for all hidden layers for every node in the layer
#weight and bias initialization wh=np.random.uniform(size=(inputlayer_neurons,hiddenlayer_neurons)) bh=np.random.uniform(size=(1,hiddenlayer_neurons)) wout=np.random.uniform(size=(hiddenlayer_neurons,output_neurons))
bout=np.random.uniform(size=(1,output_neurons))
for i in range(epoch): hinp1=np.dot(X,wh) hinp=hinp1 + bh hlayer_act = sigmoid(hinp) outinp1=np.dot(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) hiddengrad = derivatives_sigmoid(hlayer_act) #how much hidden layer wts contributed to error d_hiddenlayer = EH * hiddengrad wout += hlayer_act.T.dot(d_output) *lr
bout += np.sum(d_output, axis=0,keepdims=True) *lr wh += X.T.dot(d_hiddenlayer) *lr #bh += np.sum(d_hiddenlayer, axis=0,keepdims=True) *lr print("Input: \n" + str(X)) print("Actual Output: \n" + str(y)) print("Predicted Output: \n" ,output)
Input: [[ 0.66666667 1. ] [ 0.33333333 0.55555556] [ 1. 0.66666667]] Actual Output: [[ 0.92] [ 0.86] [ 0.89]] Predicted Output: [[ 0.89559591] [ 0.88142069] [ 0.8928407 ]]
5. Write a program to implement the naïve Bayesian classifier for a sample training data set stored as a .CSV file. Compute the accuracy of the classifier, considering few test data sets.
Problem statement:
Or
P(H) is the probability of hypothesis H being true. This is known as the prior probability. P(E) is the probability of the evidence(regardless of the hypothesis). P(E|H) is the probability of the evidence given that hypothesis is true. P(H|E) is the probability of the hypothesis given that the evidence is there.
Prior, conditional and joint probability for random variables
Prior probability: Conditional probability: Joint probability: Relationship: Independence:
Example:
Posterior = Likelihood * prior Evidence
Classifier (^5)
P ( x ) P ( x 1 |x 2 ), P(x 2 | x 1 ) x ( x 1 , x 2 ), P ( x ) P(x 1 ,x 2 ) P(x 1 ,x 2 ) P ( x 2 | x 1 ) P ( x 1 ) P ( x 1 | x 2 ) P ( x 2 ) P ( x 2 | x 1 ) P ( x 2 ), P ( x 1 | x 2 ) P ( x 1 ), P(x 1 ,x 2 ) P ( x 1 ) P ( x 2 )
x x x P P c| P |cPc