0% found this document useful (0 votes)
110 views

Lab Programs

This document describes the A* search algorithm and an AO* search algorithm. It defines a Graph class that takes in an adjacency list and heuristic values. The A* algorithm uses open and closed lists to iteratively search for the shortest path between start and stop nodes. The AO* algorithm recursively searches for the optimal solution graph by computing minimum cost child nodes and setting their statuses.

Uploaded by

Akhila R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views

Lab Programs

This document describes the A* search algorithm and an AO* search algorithm. It defines a Graph class that takes in an adjacency list and heuristic values. The A* algorithm uses open and closed lists to iteratively search for the shortest path between start and stop nodes. The AO* algorithm recursively searches for the optimal solution graph by computing minimum cost child nodes and setting their statuses.

Uploaded by

Akhila R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

In 

[2]:
#A STAR

from collections import deque

class Graph:

def __init__(self, adjac_lis):

self.adjac_lis = adjac_lis

def get_neighbors(self, v):

return self.adjac_lis[v]

# This is heuristic function which is having equal values for all nodes

def h(self, n):

H = {

'A': 1,

'B': 1,

'C': 1,

'D': 1

return H[n]

def a_star_algorithm(self, start, stop):

# In this open_lst is a lisy of nodes which have been visited, but who's

# neighbours haven't all been always inspected, It starts off with the start
#node

# And closed_lst is a list of nodes which have been visited

# and who's neighbors have been always inspected

open_lst = set([start])

closed_lst = set([])

# poo has present distances from start to all other nodes

# the default value is +infinity

poo = {}

poo[start] = 0

# par contains an adjac mapping of all nodes

par = {}

par[start] = start

while len(open_lst) > 0:

n = None

# it will find a node with the lowest value of f() -

for v in open_lst:

if n == None or poo[v] + self.h(v) < poo[n] + self.h(n):

n = v;

if n == None:

print('Path does not exist!')

return None

# if the current node is the stop

# then we start again from start

if n == stop:

reconst_path = []

while par[n] != n:

reconst_path.append(n)

n = par[n]

reconst_path.append(start)

reconst_path.reverse()

print('Path found: {}'.format(reconst_path))

return reconst_path

# for all the neighbors of the current node do

for (m, weight) in self.get_neighbors(n):

# if the current node is not presentin both open_lst and closed_lst

# add it to open_lst and note n as it's par

if m not in open_lst and m not in closed_lst:

open_lst.add(m)

par[m] = n

poo[m] = poo[n] + weight

# otherwise, check if it's quicker to first visit n, then m

# and if it is, update par data and poo data

# and if the node was in the closed_lst, move it to open_lst

else:

if poo[m] > poo[n] + weight:

poo[m] = poo[n] + weight

par[m] = n

if m in closed_lst:

closed_lst.remove(m)

open_lst.add(m)

# remove n from the open_lst, and add it to closed_lst

# because all of his neighbors were inspected

open_lst.remove(n)

closed_lst.add(n)

print('Path does not exist!')

return None

adjac_lis = {

'A': [('B', 1), ('C', 3), ('D', 7)],

'B': [('D', 5)],

'C': [('D', 12)]

graph1 = Graph(adjac_lis)

graph1.a_star_algorithm('A', 'D')

Path found: ['A', 'B', 'D']

['A', 'B', 'D']


Out[2]:

In [9]:
#AO STAR

class Graph:

def __init__(self, graph, heuristicNodeList, startNode): #instantiate graph obj


self.graph = graph

self.H=heuristicNodeList

self.start=startNode

self.parent={}

self.status={}

self.solutionGraph={}

def applyAOStar(self): # starts a recursive AO* algorithm

self.aoStar(self.start, False)

def getNeighbors(self, v): # gets the Neighbors of a given node

return self.graph.get(v,'')

def getStatus(self,v): # return the status of a given node

return self.status.get(v,0)

def setStatus(self,v, val): # set the status of a given node

self.status[v]=val

def getHeuristicNodeValue(self, n):

return self.H.get(n,0) # always return the heuristic value of a given no

def setHeuristicNodeValue(self, n, value):

self.H[n]=value # set the revised heuristic value of a given node


def printSolution(self):

print("FOR GRAPH SOLUTION, TRAVERSE THE GRAPH FROM THE START NODE:",self.sta
print("------------------------------------------------------------")

print(self.solutionGraph)
print("------------------------------------------------------------")

def computeMinimumCostChildNodes(self, v): # Computes the Minimum Cost of child


minimumCost=0

costToChildNodeListDict={}

costToChildNodeListDict[minimumCost]=[]

flag=True

for nodeInfoTupleList in self.getNeighbors(v): # iterate over all the set o


cost=0

nodeList=[]

for c, weight in nodeInfoTupleList:

cost=cost+self.getHeuristicNodeValue(c)+weight

nodeList.append(c)

if flag==True: # initialize Minimum Cost with the c


minimumCost=cost

costToChildNodeListDict[minimumCost]=nodeList # set the Minimum


flag=False
else: # checking the Minimum Cost nodes wi
if minimumCost>cost:

minimumCost=cost

costToChildNodeListDict[minimumCost]=nodeList # set the Minimum


return minimumCost, costToChildNodeListDict[minimumCost] # return Minimum


def aoStar(self, v, backTracking): # AO* algorithm for a start node and back

print("HEURISTIC VALUES :", self.H)

print("SOLUTION GRAPH :", self.solutionGraph)

print("PROCESSING NODE :", v)

print("---------------------------------------------------------------------

if self.getStatus(v) >= 0: # if status node v >= 0, compute Minimum C


minimumCost, childNodeList = self.computeMinimumCostChildNodes(v)

self.setHeuristicNodeValue(v, minimumCost)

self.setStatus(v,len(childNodeList))

solved=True # check the Minimum Cost nodes of v are so


for childNode in childNodeList:

self.parent[childNode]=v

if self.getStatus(childNode)!=-1:

solved=solved & False

if solved==True: # if the Minimum Cost nodes of v are solved


self.setStatus(v,-1)
self.solutionGraph[v]=childNodeList # update the solution graph with

if v!=self.start: # check the current node is the start node f


self.aoStar(self.parent[v], True) # backtracking the current node

if backTracking==False: # check the current call is not for backtrac


for childNode in childNodeList: # for each Minimum Cost child node
self.setStatus(childNode,0) # set the status of child node to
self.aoStar(childNode, False) # Minimum Cost child node is furth

h1 = {'A': 1, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 5, 'H': 7, 'I': 7, 'J':
graph1 = {

'A': [[('B', 1), ('C', 1)], [('D', 1)]],

'B': [[('G', 1)], [('H', 1)]],

'C': [[('J', 1)]],

'D': [[('E', 1), ('F', 1)]],

'G': [[('I', 1)]]

G1= Graph(graph1, h1, 'A')

G1.applyAOStar()

G1.printSolution()

# h2 = {'A': 1, 'B': 6, 'C': 12, 'D': 10, 'E': 4, 'F': 4, 'G': 5, 'H': 7} # Heurist
# graph2 = { # Graph of Nodes and Edges

# 'A': [[('B', 1), ('C', 1)], [('D', 1)]], # Neighbors of Node 'A', B, C &
# 'B': [[('G', 1)], [('H', 1)]], # Neighbors are included in a li
# 'D': [[('E', 1), ('F', 1)]] # Each sublist indicate a "OR" n
# }

# G2 = Graph(graph2, h2, 'A') # Instantiate Graph object with


# G2.applyAOStar() # Run the AO* algorithm

# G2.printSolution() # Print the solution graph as ou

HEURISTIC VALUES : {'A': 1, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 5, 'H':
7, 'I': 7, 'J': 1, 'T': 3}

SOLUTION GRAPH : {}

PROCESSING NODE : A

------------------------------------------------------------------------------------
-----

HEURISTIC VALUES : {'A': 10, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 5, 'H':
7, 'I': 7, 'J': 1, 'T': 3}

SOLUTION GRAPH : {}

PROCESSING NODE : B

------------------------------------------------------------------------------------
-----

HEURISTIC VALUES : {'A': 10, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 5, 'H':
7, 'I': 7, 'J': 1, 'T': 3}

SOLUTION GRAPH : {}

PROCESSING NODE : A

------------------------------------------------------------------------------------
-----

HEURISTIC VALUES : {'A': 10, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 5, 'H':
7, 'I': 7, 'J': 1, 'T': 3}

SOLUTION GRAPH : {}

PROCESSING NODE : G

------------------------------------------------------------------------------------
-----

HEURISTIC VALUES : {'A': 10, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 8, 'H':
7, 'I': 7, 'J': 1, 'T': 3}

SOLUTION GRAPH : {}

PROCESSING NODE : B

------------------------------------------------------------------------------------
-----

HEURISTIC VALUES : {'A': 10, 'B': 8, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 8, 'H':
7, 'I': 7, 'J': 1, 'T': 3}

SOLUTION GRAPH : {}

PROCESSING NODE : A

------------------------------------------------------------------------------------
-----

HEURISTIC VALUES : {'A': 12, 'B': 8, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 8, 'H':
7, 'I': 7, 'J': 1, 'T': 3}

SOLUTION GRAPH : {}

PROCESSING NODE : I

------------------------------------------------------------------------------------
-----

HEURISTIC VALUES : {'A': 12, 'B': 8, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 8, 'H':
7, 'I': 0, 'J': 1, 'T': 3}

SOLUTION GRAPH : {'I': []}

PROCESSING NODE : G

------------------------------------------------------------------------------------
-----

HEURISTIC VALUES : {'A': 12, 'B': 8, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H':
7, 'I': 0, 'J': 1, 'T': 3}

SOLUTION GRAPH : {'I': [], 'G': ['I']}

PROCESSING NODE : B

------------------------------------------------------------------------------------
-----

HEURISTIC VALUES : {'A': 12, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H':
7, 'I': 0, 'J': 1, 'T': 3}

SOLUTION GRAPH : {'I': [], 'G': ['I'], 'B': ['G']}

PROCESSING NODE : A

------------------------------------------------------------------------------------
-----

HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H':
7, 'I': 0, 'J': 1, 'T': 3}

SOLUTION GRAPH : {'I': [], 'G': ['I'], 'B': ['G']}

PROCESSING NODE : C

------------------------------------------------------------------------------------
-----

HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H':
7, 'I': 0, 'J': 1, 'T': 3}

SOLUTION GRAPH : {'I': [], 'G': ['I'], 'B': ['G']}

PROCESSING NODE : A

------------------------------------------------------------------------------------
-----

HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H':
7, 'I': 0, 'J': 1, 'T': 3}

SOLUTION GRAPH : {'I': [], 'G': ['I'], 'B': ['G']}

PROCESSING NODE : J

------------------------------------------------------------------------------------
-----

HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H':
7, 'I': 0, 'J': 0, 'T': 3}

SOLUTION GRAPH : {'I': [], 'G': ['I'], 'B': ['G'], 'J': []}

PROCESSING NODE : C

------------------------------------------------------------------------------------
-----

HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 1, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H':
7, 'I': 0, 'J': 0, 'T': 3}

SOLUTION GRAPH : {'I': [], 'G': ['I'], 'B': ['G'], 'J': [], 'C': ['J']}

PROCESSING NODE : A

------------------------------------------------------------------------------------
-----

FOR GRAPH SOLUTION, TRAVERSE THE GRAPH FROM THE START NODE: A

------------------------------------------------------------

{'I': [], 'G': ['I'], 'B': ['G'], 'J': [], 'C': ['J'], 'A': ['B', 'C']}

------------------------------------------------------------

In [7]:
#ID3 ALGORITHM

import pandas as pd

import math

import numpy as np

data = pd.read_csv("3-dataset.csv")

features = [feat for feat in data]

features.remove("answer")

class Node:

def __init__(self):

self.children = []

self.value = ""

self.isLeaf = False

self.pred = ""

def entropy(examples):

pos = 0.0

neg = 0.0

for _, row in examples.iterrows():

if row["answer"] == "yes":

pos += 1

else:

neg += 1

if pos == 0.0 or neg == 0.0:

return 0.0

else:

p = pos / (pos + neg)

n = neg / (pos + neg)

return -(p * math.log(p, 2) + n * math.log(n, 2))

def info_gain(examples, attr):

uniq = np.unique(examples[attr])

#print ("\n",uniq)

gain = entropy(examples)

#print ("\n",gain)

for u in uniq:

subdata = examples[examples[attr] == u]
#print ("\n",subdata)

sub_e = entropy(subdata)

gain -= (float(len(subdata)) / float(len(examples))) * sub_e

#print ("\n",gain)
return gain

def ID3(examples, attrs):

root = Node()

max_gain = 0

max_feat = ""

for feature in attrs:

#print ("\n",examples)

gain = info_gain(examples, feature)

if gain > max_gain:

max_gain = gain

max_feat = feature

root.value = max_feat

#print ("\nMax feature attr",max_feat)

uniq = np.unique(examples[max_feat])

#print ("\n",uniq)

for u in uniq:

#print ("\n",u)

subdata = examples[examples[max_feat] == u]

#print ("\n",subdata)

if entropy(subdata) == 0.0:

newNode = Node()

newNode.isLeaf = True
newNode.value = u

newNode.pred = np.unique(subdata["answer"])

root.children.append(newNode)

else:

dummyNode = Node()

dummyNode.value = u

new_attrs = attrs.copy()

new_attrs.remove(max_feat)

child = ID3(subdata, new_attrs)

dummyNode.children.append(child)

root.children.append(dummyNode)

return root

def printTree(root: Node, depth=0):

for i in range(depth):

print("\t", end="")

print(root.value, end="")

if root.isLeaf:

print(" -> ", root.pred)

print()

for child in root.children:

printTree(child, depth + 1)

root = ID3(data, features)

printTree(root)

outlook

overcast -> ['yes']

rain

wind

strong -> ['no']

weak -> ['yes']

sunny

humidity

high -> ['no']

normal -> ['yes']

In [8]:
#NAVIE BAYESIAN CLASSIFIER

import pandas as pd

# from sklearn.model_selection import train_test_split

from sklearn.model_selection import train_test_split

#to model the Gaussian Navie Bayes Classifier

from sklearn.naive_bayes import GaussianNB

#to calculate the accuracy score of the model

from sklearn.metrics import accuracy_score

DB = pd.read_csv('tennis1.csv')

print(DB.columns)

len(DB)

DB.head(3)

X = DB.values[:,0:4] #Features

Y = DB.values[:,4] #Target

#split the data into train and test

X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.30,random_state=10)
#implement Gaussian Naive Bayes

clf = GaussianNB()

clf.fit(X_train,Y_train)

Y_pred = clf.predict(X_test)

#accuracy of the GNB

accuracy_score(Y_test,Y_pred,normalize=True)

Index(['Day', 'Temperature', 'Humidity', 'Windy', 'Play'], dtype='object')

1.0
Out[8]:

In [3]:
#CANDIDATE ELIMINATION

import csv

with open("ws.csv") as f:

csv_file=csv.reader(f)

data=list(csv_file)

s=data[0][:-1]

g=[['?' for i in range(len(s))]for j in range(len(s))]

for i in range(len(s)):

for j in range(len(s)):

g[i][j]='?'

for i in data:

if i[-1]=="Yes":

for j in range(len(s)):

if i[j]!=s[j]:

s[j]='?'

g[j][j]='?'

elif i[-1]=="No":

for j in range(len(s)):

if i[j]!=s[j]:

g[j][j]=s[j]

else:

g[j][j]="?"

print("\nSteps of Candidate Elimination Algorithm",data.index(i)+1)

print(s)

print(g)

gh=[]

for i in g:

for j in i:

if j!='?':

gh.append(i)

break

print("\nFinal specific hypothesis:\n",s)

print("\nFinal general hypothesis:\n",gh)

Steps of Candidate Elimination Algorithm 1

['Sunny', 'Warm', 'Normal', 'Strong', 'Warm', 'Same']

[['?', '?', '?', '?', '?', '?'], ['?', '?', '?', '?', '?', '?'], ['?', '?', '?',
'?', '?', '?'], ['?', '?', '?', '?', '?', '?'], ['?', '?', '?', '?', '?', '?'],
['?', '?', '?', '?', '?', '?']]

Steps of Candidate Elimination Algorithm 2

['Sunny', 'Warm', '?', 'Strong', 'Warm', 'Same']

[['?', '?', '?', '?', '?', '?'], ['?', '?', '?', '?', '?', '?'], ['?', '?', '?',
'?', '?', '?'], ['?', '?', '?', '?', '?', '?'], ['?', '?', '?', '?', '?', '?'],
['?', '?', '?', '?', '?', '?']]

Steps of Candidate Elimination Algorithm 3

['Sunny', 'Warm', '?', 'Strong', 'Warm', 'Same']

[['Sunny', '?', '?', '?', '?', '?'], ['?', 'Warm', '?', '?', '?', '?'], ['?', '?',
'?', '?', '?', '?'], ['?', '?', '?', '?', '?', '?'], ['?', '?', '?', '?', '?', '?'],
['?', '?', '?', '?', '?', 'Same']]

Steps of Candidate Elimination Algorithm 4

['Sunny', 'Warm', '?', 'Strong', '?', '?']

[['Sunny', '?', '?', '?', '?', '?'], ['?', 'Warm', '?', '?', '?', '?'], ['?', '?',
'?', '?', '?', '?'], ['?', '?', '?', '?', '?', '?'], ['?', '?', '?', '?', '?', '?'],
['?', '?', '?', '?', '?', '?']]

Final specific hypothesis:

['Sunny', 'Warm', '?', 'Strong', '?', '?']

Final general hypothesis:

[['Sunny', '?', '?', '?', '?', '?'], ['?', 'Warm', '?', '?', '?', '?']]

In [16]:
#BACKPROPAGATION ALGORITHM

import numpy as np

def sigmoid (x):

return 1/(1 + np.exp(-x))

def sigmoid_derivative(x):

return x * (1 - x)

inputs = np.array([[0,0],[0,1],[1,0],[1,1]])

expected_output = np.array([[0],[1],[1],[0]])

epochs = 10000

lr = 0.1

inputLayerNeurons, hiddenLayerNeurons, outputLayerNeurons = 2,2,1

hidden_weights = np.random.uniform(size=(inputLayerNeurons,hiddenLayerNeurons))

hidden_bias =np.random.uniform(size=(1,hiddenLayerNeurons))

output_weights = np.random.uniform(size=(hiddenLayerNeurons,outputLayerNeurons))

output_bias = np.random.uniform(size=(1,outputLayerNeurons))

print("Initial hidden weights: ",end='')

print(*hidden_weights)

print("Initial hidden biases: ",end='')

print(*hidden_bias)

print("Initial output weights: ",end='')

print(*output_weights)

print("Initial output biases: ",end='')

print(*output_bias)

for _ in range(epochs):

hidden_layer_activation = np.dot(inputs,hidden_weights)

hidden_layer_activation += hidden_bias

hidden_layer_output = sigmoid(hidden_layer_activation)

output_layer_activation = np.dot(hidden_layer_output,output_weights)

output_layer_activation += output_bias

predicted_output = sigmoid(output_layer_activation)

error = expected_output - predicted_output

d_predicted_output = error * sigmoid_derivative(predicted_output)

error_hidden_layer = d_predicted_output.dot(output_weights.T)

d_hidden_layer = error_hidden_layer * sigmoid_derivative(hidden_layer_output)

output_weights += hidden_layer_output.T.dot(d_predicted_output) * lr

output_bias += np.sum(d_predicted_output,axis=0,keepdims=True) * lr

hidden_weights += inputs.T.dot(d_hidden_layer) * lr

hidden_bias += np.sum(d_hidden_layer,axis=0,keepdims=True) * lr

print("Final hidden weights: ",end='')

print(*hidden_weights)

print("Final hidden bias: ",end='')

print(*hidden_bias)

print("Final output weights: ",end='')

print(*output_weights)

print("Final output bias: ",end='')

print(*output_bias)

print("\nOutput from neural network after 10,000 epochs: ",end='')

print(*predicted_output)

Initial hidden weights: [0.82904118 0.16446024] [0.22327349 0.98372656]

Initial hidden biases: [0.7237147 0.33322324]

Initial output weights: [0.60618933] [0.59310177]

Initial output biases: [0.59473799]

Final hidden weights: [3.60915604 5.61102965] [3.5916564 5.61497663]

Final hidden bias: [ 0.5741952 -0.79933304]

Final output weights: [0.77328285] [4.1298489]

Final output bias: [-4.19929254]

Output from neural network after 10,000 epochs: [0.08139583] [0.6589966] [0.6590127
1] [0.66893982]

In [13]:
#K-MEANS ALGORITM USING EM ALGORITHM

from sklearn import datasets

from sklearn.cluster import KMeans

from sklearn.model_selection import train_test_split

from sklearn import metrics

iris = datasets.load_iris()

X_train,X_test,Y_train,Y_test = train_test_split(iris.data,iris.target)

model = KMeans(n_clusters=3)

model.fit(X_train,Y_train)

model.score

acc1=metrics.accuracy_score(Y_test,model.predict(X_test))

print(acc1)

from sklearn.mixture import GaussianMixture

model2 = GaussianMixture(n_components=3)

model2.fit(X_train,Y_train)

model2.score

metrics

acc2=metrics.accuracy_score(Y_test,model.predict(X_test))

print(acc2)

0.5263157894736842

0.5263157894736842

In [15]:
from sklearn.model_selection import train_test_split

from sklearn.neighbors import KNeighborsClassifier

from sklearn.metrics import classification_report,confusion_matrix

from sklearn import datasets

iris=datasets.load_iris()

iris_data=iris.data

iris_labels=iris.target

x_train,x_test,y_train,y_test=train_test_split(iris_data,iris_labels,test_size=0.30)
classifier=KNeighborsClassifier(n_neighbors=5)

classifier.fit(x_train,y_train)

y_pred=classifier.predict(x_test)

print('Confusion matrix is as follows')

print(confusion_matrix(y_test,y_pred))

print('Accuracy Matrics')

print(classification_report(y_test,y_pred))

Confusion matrix is as follows

[[14 0 0]

[ 0 13 0]

[ 0 3 15]]

Accuracy Matrics

precision recall f1-score support

0 1.00 1.00 1.00 14

1 0.81 1.00 0.90 13

2 1.00 0.83 0.91 18

accuracy 0.93 45

macro avg 0.94 0.94 0.94 45

weighted avg 0.95 0.93 0.93 45

In [19]:
import matplotlib.pyplot as plt

import pandas as pd

import numpy as np1

def kernel(point,xmat, k):

m,n= np1.shape(xmat)

weights = np1.mat(np1.eye((m)))

for j in range(m):

diff = point - X[j]

weights[j,j] = np1.exp(diff*diff.T/(-2.0*k**2))

return weights

def localWeight(point,xmat,ymat,k):

wei = kernel(point,xmat,k)

W = (X.T*(wei*X)).I*(X.T*(wei*ymat.T))

return W

def localWeightRegression(xmat,ymat,k):

m,n = np1.shape(xmat)

ypred = np1.zeros(m)

for i in range(m):

ypred[i] = xmat[i]*localWeight(xmat[i],xmat,ymat,k)

return ypred

data = pd.read_csv('prg9tips.csv')

bill = np1.array(data.total_bill)

tip = np1.array(data.tip)

mbill = np1.mat(bill)

mtip = np1.mat(tip)

m= np1.shape(mbill)[1]

print("******",m)

one = np1.mat(np1.ones(m))

X= np1.hstack((one.T,mbill.T))

ypred = localWeightRegression(X,mtip,2)
SortIndex = X[:,1].argsort(0)

xsort = X[SortIndex][:,0]

fig = plt.figure()

ax = fig.add_subplot(1,1,1)

ax.scatter(bill,tip, color='blue')

ax.plot(xsort[:,1],ypred[SortIndex], color = 'red', linewidth=1)

plt.xlabel('Total bill')

plt.ylabel('Tip')

plt.show();

---------------------------------------------------------------------------

FileNotFoundError Traceback (most recent call last)

~\AppData\Local\Temp/ipykernel_3268/3362905836.py in <module>

21 ypred[i] = xmat[i]*localWeight(xmat[i],xmat,ymat,k)

22 return ypred

---> 23 data = pd.read_csv('prg9tips.csv')

24 bill = np1.array(data.total_bill)

25 tip = np1.array(data.tip)

~\Anaconda3\lib\site-packages\pandas\util\_decorators.py in wrapper(*args, **kwargs)

309 stacklevel=stacklevel,

310 )

--> 311 return func(*args, **kwargs)

312

313 return wrapper

~\Anaconda3\lib\site-packages\pandas\io\parsers\readers.py in read_csv(filepath_or_b
uffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_du
pe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, ski
prows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank
_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, ca
che_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quo
techar, quoting, doublequote, escapechar, comment, encoding, encoding_errors, dialec
t, error_bad_lines, warn_bad_lines, on_bad_lines, delim_whitespace, low_memory, memo
ry_map, float_precision, storage_options)

584 kwds.update(kwds_defaults)

585

--> 586 return _read(filepath_or_buffer, kwds)

587

588

~\Anaconda3\lib\site-packages\pandas\io\parsers\readers.py in _read(filepath_or_buff
er, kwds)

480

481 # Create the parser.

--> 482 parser = TextFileReader(filepath_or_buffer, **kwds)

483

484 if chunksize or iterator:

~\Anaconda3\lib\site-packages\pandas\io\parsers\readers.py in __init__(self, f, engi


ne, **kwds)

809 self.options["has_index_names"] = kwds["has_index_names"]

810

--> 811 self._engine = self._make_engine(self.engine)

812

813 def close(self):

~\Anaconda3\lib\site-packages\pandas\io\parsers\readers.py in _make_engine(self, eng


ine)

1038 )

1039 # error: Too many arguments for "ParserBase"

-> 1040 return mapping[engine](self.f, **self.options) # type: ignore[call-


arg]

1041

1042 def _failover_to_python(self):

~\Anaconda3\lib\site-packages\pandas\io\parsers\c_parser_wrapper.py in __init__(sel
f, src, **kwds)

49

50 # open handles

---> 51 self._open_handles(src, kwds)

52 assert self.handles is not None

53

~\Anaconda3\lib\site-packages\pandas\io\parsers\base_parser.py in _open_handles(sel
f, src, kwds)

220 Let the readers open IOHandles after they are done with their potent
ial raises.

221 """

--> 222 self.handles = get_handle(

223 src,

224 "r",

~\Anaconda3\lib\site-packages\pandas\io\common.py in get_handle(path_or_buf, mode, e


ncoding, compression, memory_map, is_text, errors, storage_options)

700 if ioargs.encoding and "b" not in ioargs.mode:

701 # Encoding

--> 702 handle = open(


703 handle,

704 ioargs.mode,

FileNotFoundError: [Errno 2] No such file or directory: 'prg9tips.csv'

In [ ]:

You might also like