Posts

Showing posts from January, 2024

PROG9

 import matplotlib.pyplot as plt import pandas as pd import numpy as np def kernel(point, xmat, k):     m, n = np.shape(xmat)     weights = np.mat(np.eye((m)))  # eye - identity matrix     for j in range(m):         diff = point - X[j]         weights[j, j] = np.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 = np.shape(xmat)     ypred = np.zeros(m)     for i in range(m):         ypred[i] = xmat[i] * localWeight(xmat[i], xmat, ymat, k)     return ypred def graphPlot(X, ypred):     sortindex = X[:, 1].argsort(0)  # argsort - index of the smallest     xsort = X[sortindex][:, 0]     fig = plt.figure()     ax = fig.add_subplot(1, 1, 1)     ax.scatter(bill, tip, color='green')     ax.plot(xsort[:, 1], ypred[sortindex], color='red', linewidth=5)     plt.xlabel('Total bill')  

PROG8

 from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn import datasets # Load dataset iris = datasets.load_iris() print("Iris Data set loaded...") # Split the data into train and test samples x_train, x_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.1) print("Dataset is split into training and testing...") print("Size of training data and its label", x_train.shape, y_train.shape) print("Size of testing data and its label", x_test.shape, y_test.shape) # Prints Label no. and their names for i in range(len(iris.target_names)):     print("Label", i, "-", str(iris.target_names[i])) # Create object of KNN classifier classifier = KNeighborsClassifier(n_neighbors=12) # Perform Training classifier.fit(x_train, y_train) # Perform testing y_pred = classifier.predict(x_test) # Display the results print("Results of Classification using K-nn wi

PROG6

 import pandas as pd from sklearn.model_selection import train_test_split from sklearn.naive_bayes import GaussianNB from sklearn import metrics df=pd.read_csv("pima_indian.csv") feature_col_names=['num_preg','glucose_conc','diastolic_bp','thickness','insulin','bmi','diab_pred','num_preg','age'] predicted_class_names=['diabetes'] x=df[feature_col_names].values y=df[predicted_class_names].values xtrain,xtest,ytrain,ytest=train_test_split(x,y,test_size=0.33) print('\n total numbe of training data:',ytrain.shape) print('\n total numbe of test data:',ytest.shape) clf=GaussianNB().fit(xtrain,ytrain.ravel()) predicted=clf.predict(xtest) predictTestData=clf.predict([[16,146,72,35,0,33.6,0.627,50,1]]) print('\n Confusion_matrix:',metrics.confusion_matrix(ytest,predicted)) print('\n accuracy of classifier:',metrics.accuracy_score(ytest,predicted)) print('\n the value of

PROG5

 import numpy as np x=np.array(([2,4],[5,6],[3,6]),dtype=float) y=np.array(([92],[83],[89]),dtype=float) x=x/np.amax(x,axis=0) y=y/100 def sigmoid(x):     return 1/(1+np.exp(-x)) def derivatives_sigmoid(x):     return x*(1-x) epoch=5000 lr=0.1 inputlayer_neurons=2 hiddenlayer_neurons=3 output_neurons=1 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)     EO=y-output     outgrad=derivatives_sigmoid(output)     d_output=EO*outgrad     EH=d_output.dot(wout.T) hiddengrad=derivatives_sigmoid(hlayer_act) d_hiddenlayer =EH*hiddengrad wout+=hlayer_act.T.dot(d_output)*lr wh+=x.T.dot(d_hiddenlayer)*lr print("INPUT:\n"+str(x)) pr

PROG4

 import math import csv def load_csv(filename):     lines = csv.reader(open(filename, "r"))     dataset = list(lines)     headers = dataset.pop(0)     return dataset, headers class Node:     def __init__(self, attribute):         self.attribute = attribute         self.children = []         self.answer = "" def subtables(data, col, delete):     dic = {}     coldata = [row[col] for row in data]     attr = list(set(coldata))          for k in attr:         dic[k] = []              for y in range(len(data)):         key = data[y][col]         if delete:             del data[y][col]         dic[key].append(data[y])          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 * math.log(cnt, 2)          return sums def compute_gain(d

PROG3

 import numpy as np import pandas as pd data=data = pd.read_csv("2_candidate.csv") concepts = np.array(data.iloc[:, 0:-1]) target = np.array(data.iloc[:, -1]) def learn(concepts, target):     specific_h = concepts[0].copy()     general_h = [["?" for i in range(len(specific_h))]                  for i in range(len(specific_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] = '?'                     general_h[x][x] = '?'         if target[i] == "no":             for x in range(len(specific_h)):                 if h[x] != specific_h[x]:                     general_h[x][x] = specific_h[x]                 else:                     general_h[x][x] = '?'     indices = [i for i, val in enumerate(general_h) if val == ['?','?','?','?','?','?']]

PROG2

 class Graph:     def __init__(self, graph, heuristicNodeList, startNode):         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):         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)     def setHeuristicNodeValue(self, n, value):         self.H[n] = value     def printSolution(self):         print("FOR GRAPH SOLUTION, TRAVERSE THE GRAPH FROM THE START NODE:", self.start)         print("-----------------------------------------------")         print(self.solutio

PROG1

def aStarAlgo(start_node, stop_node):     open_set = set([start_node])     closed_set = set()     g = {}     parents = {}     g[start_node] = 0     parents[start_node] = start_node     while len(open_set) > 0:         n = None         for v in open_set:             if n is None or g[v] + heuristic(v) < g[n] + heuristic(n):                 n = v         if n == stop_node or Graph_nodes[n] is None:             pass         else:             for (m, weight) in get_neighbors(n):                 if m not in open_set and m not in closed_set:                     open_set.add(m)                     parents[m] = n                     g[m] = g[n] + weight                 else:                     if g[m] > g[n] + weight:                         g[m] = g[n] + weight                         parents[m] = n                         if m in closed_set:                             closed_set.remove(m)                             open_set.add(m)         if n is None:             print('Path