0% found this document useful (0 votes)
3 views1 page

Ailmml

The document contains various algorithms and methods including A*, AO*, and water jug problem solvers, as well as machine learning techniques like Find-S, backpropagation, and Bayesian inference for heart disease prediction. It demonstrates the implementation of these algorithms using Python code, showcasing their respective functionalities and applications. Additionally, it includes a section on Bayes Theorem for calculating conditional probabilities.

Uploaded by

girnimussaib
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)
3 views1 page

Ailmml

The document contains various algorithms and methods including A*, AO*, and water jug problem solvers, as well as machine learning techniques like Find-S, backpropagation, and Bayesian inference for heart disease prediction. It demonstrates the implementation of these algorithms using Python code, showcasing their respective functionalities and applications. Additionally, it includes a section on Bayes Theorem for calculating conditional probabilities.

Uploaded by

girnimussaib
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/ 1

A* algorithm AO* Algorithm Water_jug

import heapq graph = { from collections import deque


def astar (start, goal, neighbours, h): 'A': [(['B', 'C'], 3)], def water_jug_solver(jug1, jug2, target):
open_set=[(h (start), 0, start, [])] 'B': [(['D'], 1)], visited = set()
visited = set() 'C': [(['E', 'F'], 2)], queue = deque([(0, 0)])
while open_set: 'D': [], while queue:
f,g, node, path = heapq.heappop(open_set) 'E': [], j1, j2 = queue.popleft()
if node in visited: continue 'F': [] if (j1, j2) in visited:
if node == goal: return path + [node] } continue
visited.add(node) heuristic = {'A': 5, 'B': 2, 'C': 4, 'D': 0, 'E': 0, 'F': 0} visited.add((j1, j2))
for nbr, cost in neighbours (node): solved = {} print((j1, j2))
if nbr not in visited: path = {} if j1 == target or j2 == target:
heapq.heappush (open_set, (g+cost+h(nbr), def AOStar(node): return
g+cost, nbr, path+[node])) if node in solved: possible_moves = [
def neighbours (node): return heuristic[node] (jug1, j2),
graph={ min_cost = float('inf') (j1, jug2),
'A': [('B', 1), ('C', 3)], best_children = [] (0, j2),
'B': [('D', 1)], for children, cost in graph.get(node, []): (j1, 0),
'C': [('D', 1)], h = cost + sum(AOStar(child) for child in children) (j1 - min(j1, jug2 - j2), j2 + min(j1, jug2 - j2)),
'D': [] if h < min_cost: (j1 + min(j2, jug1 - j1), j2 - min(j2, jug1 - j1))
} min_cost = total_cost ]
return graph [node] best_children = children for move in possible_moves:
heuristic={ heuristic[node] = min_cost if move not in visited:
'A': 2, 'B': 1, 'C': 1, 'D':0 path[node] = best_children queue.append(move)
} if all(child in solved for child in best_children): jug1_capacity = 4
def h(n): return heuristic[n] solved[node] = True jug2_capacity = 3
path = astar ('A', 'D', neighbours,h) return heuristic[node] target_amount = 2
print("Shortest path:", path) AOStar('A') print("Steps to get", target_amount, "litres:")
print('Optimal Path:', path) water_jug_solver(jug1_capacity, jug2_capacity,
target_amount)

Find-S Algorithm Back propogation CEA


import numpy as np import numpy as np import numpy as np
def find_s_algorithm(data, target): X = np.array([[0,0],[0,1],[1,0],[1,1]]) import pandas as pd
hypothesis = None y = np.array([[0],[1],[1],[0]]) file_path = "CEA Data Set.csv"
for i, val in enumerate(target): np.random.seed() df = pd.read_csv(file_path)
if val == "Yes": w1 = np.random.rand(2,2) attributes = df.iloc[:, :-1].values
hypothesis = data[i] w2 = np.random.rand(2,1) target = df.iloc[:, -1].values
break b1, b2 = np.zeros((1,2)), np.zeros((1,1)) num_attributes = attributes.shape[1]
if hypothesis is None: for _ in range(10000): S = ['?'] * num_attributes
return "No Positive example found" h = 1 / (1 + np.exp(-(X @ w1 + b1))) G = [['?'] * num_attributes]
for i, val in enumerate(data): o = 1 / (1 + np.exp(-(h @ w2 + b2))) for i, instance in enumerate(attributes):
if target[i] == "Yes": d2 = (y - o) * o * (1 - o) if target[i] == "Yes":
for j in range(len(hypothesis)): d1 = d2 @ w2.T * h * (1 - h) for j in range(num_attributes):
if hypothesis[j] != val[j]: w2 += h.T @ d2 * 0.5 if S[j] == '?':
hypothesis[j] = "?" w1 += X.T @ d1 * 0.5 S[j] = instance[j]
return hypothesis b2 += np.sum(d2, axis=0, keepdims=True) * 0.5 elif S[j] != instance[j]:
data = np.array([ b1 += np.sum(d1, axis=0, keepdims=True) * 0.5 S[j] = '?'
['green','hard','no','wrinkled'], print(1 / (1 + np.exp(-(1 / (1 + np.exp(-(X @ w1 + b1))) G = [g for g in G if all(g[j] == '?' or g[j] == S[j] for j in
['green','hard','yes','smooth'], @ w2 + b2)))) range(num_attributes))]
['brown','soft','yes','wrinkled'], else:
['brown','hard','yes','wrinkled'], new_G = []
['green','soft','yes','smooth'], for g in G:
['green','soft','yes','wrinkled'], for j in range(num_attributes):
['orange','hard','no','wrinkled'] if g[j] == '?':
]) new_hypothesis = g.copy()
target = new_hypothesis[j] = S[j]
np.array(["Yes","No","No","Yes","Yes","Yes","Yes"]) if new_hypothesis not in new_G:
hypothesis = find_s_algorithm(data, target) new_G.append(new_hypothesis)
print("Final Hypothesis:", hypothesis) G = new_G
print("Most Specific Hypothesis (S):", S)
print("Most General Hypothesis (G):", G)
Heart Disease model.fit(df, estimator = MaximumLikelihoodEstimator) Bayes Theorem
import pandas as pd infer = VariableElimination(model) def bayes_theorem(P_A_and_B, P_B):
from sklearn.preprocessing import KBinsDiscretizer evidence = { return P_A_and_B / P_B
from pgmpy.models import BayesianNetwork "age": 1, P_A_and_B = 0.03
from pgmpy.estimators import "sex": 1, P_B = 0.20
MaximumLikelihoodEstimator "cp": 1, P_A_given_B = bayes_theorem(P_A_and_B, P_B)
from pgmpy.inference import VariableElimination "thalach": 1, print(f"The probability that a student is absent given that
"exang": 1, today is Friday: {P_A_given_B:.2f} or {P_A_given_B *
df = pd.read_csv("HeartDisease.csv") "oldpeak": 1, 100:.2f}%")
columns = ["age", "sex", "cp", "trestbps", "chol", "fbs", "ca": 1,
"restecg", "thal": 2
"thalach", "exang", "oldpeak", "slope", "ca", "thal", }
"target"] result = infer.map_query(variables = ["Heart Disease"],
df = df[columns] evidence = evidence)
df.rename(columns = {'target': 'Heart Disease'}, inplace = print("Heart Disease prediction:", result)
True)
cont_features = ["age", "trestbps", "chol", "thalach",
"oldpeak"]
disc = KBinsDiscretizer(n_bins = 3, encode = 'ordinal',
strategy = 'uniform')
df[cont_features] = disc.fit_transform(df[cont_features])
df = df.astype(int)
model = DiscreteBayesianNetwork([
("age", "Heart Disease"),
("sex", "Heart Disease"),
("cp", "Heart Disease"),
("chol", "Heart Disease"),
("thalach", "Heart Disease"),
("exang", "Heart Disease"),
("oldpeak", "Heart Disease"),
("ca", "Heart Disease"),
("thal", "Heart Disease"),
])

You might also like