0% found this document useful (0 votes)
6 views5 pages

AI and ML Code Explained CSV

Uploaded by

shanejo1506
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)
6 views5 pages

AI and ML Code Explained CSV

Uploaded by

shanejo1506
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

AI and ML Code Implementations (with CSV + Explanations)

1. Breadth-First Search (BFS)

from collections import deque

def bfs(graph, start):


visited = set()
queue = deque([start])
result = []

while queue:
node = [Link]()
if node not in visited:
[Link](node)
[Link](node)
[Link](graph[node])
return result

graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}

print("BFS Traversal:", bfs(graph, 'A'))

2. Depth-First Search (DFS)

def dfs(graph, start, visited=None):


if visited is None:
visited = set()
[Link](start)
print(start, end=' ')
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)

graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
AI and ML Code Implementations (with CSV + Explanations)

print("DFS Traversal:")
dfs(graph, 'A')

3. A* Search

from queue import PriorityQueue

def a_star(start, goal, graph, heuristics):


open_list = PriorityQueue()
open_list.put((0, start))
came_from = {}
cost_so_far = {start: 0}

while not open_list.empty():


_, current = open_list.get()
if current == goal:
break

for neighbor, cost in graph[current]:


new_cost = cost_so_far[current] + cost
if neighbor not in cost_so_far or new_cost < cost_so_far[neighbor]:
cost_so_far[neighbor] = new_cost
priority = new_cost + heuristics[neighbor]
open_list.put((priority, neighbor))
came_from[neighbor] = current

path = []
while goal in came_from:
[Link](goal)
goal = came_from[goal]
[Link](start)
[Link]()
return path

graph = {
'A': [('B', 1), ('C', 4)],
'B': [('C', 2), ('D', 5)],
'C': [('D', 1)],
'D': []
}
heuristics = {'A': 7, 'B': 6, 'C': 2, 'D': 0}
print("A* Path:", a_star('A', 'D', graph, heuristics))

4. Memory-Bounded A*

# Simplified Memory-Bounded A* using Iterative Deepening A*


AI and ML Code Implementations (with CSV + Explanations)

from queue import PriorityQueue

def ida_star(start, goal, graph, heuristics):


def search(path, g, bound):
node = path[-1]
f = g + heuristics[node]
if f > bound:
return f
if node == goal:
return path
min_cost = float('inf')
for neighbor, cost in [Link](node, []):
if neighbor not in path:
t = search(path + [neighbor], g + cost, bound)
if isinstance(t, list):
return t
if t < min_cost:
min_cost = t
return min_cost

bound = heuristics[start]
path = [start]
while True:
t = search(path, 0, bound)
if isinstance(t, list):
return t
if t == float('inf'):
return None
bound = t

graph = {
'A': [('B', 1), ('C', 4)],
'B': [('C', 2), ('D', 5)],
'C': [('D', 1)],
'D': []
}
heuristics = {'A': 7, 'B': 6, 'C': 2, 'D': 0}
print("IDA* Path:", ida_star('A', 'D', graph, heuristics))

5. Naïve Bayes (CSV)

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from [Link] import accuracy_score

data = pd.read_csv('your_dataset.csv') # Replace with your CSV file


print([Link]())
AI and ML Code Implementations (with CSV + Explanations)

X = [Link][:, :-1]
y = [Link][:, -1]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)


model = GaussianNB()
[Link](X_train, y_train)
y_pred = [Link](X_test)
print("Naïve Bayes Accuracy:", accuracy_score(y_test, y_pred))

6. Bayesian Networks

from [Link] import BayesianModel


from [Link] import TabularCPD
from [Link] import VariableElimination

model = BayesianModel([('Rain', 'Traffic'), ('Accident', 'Traffic')])

cpd_rain = TabularCPD('Rain', 2, [[0.7], [0.3]])


cpd_accident = TabularCPD('Accident', 2, [[0.9], [0.1]])
cpd_traffic = TabularCPD('Traffic', 2,
[[0.9, 0.6, 0.7, 0.1],
[0.1, 0.4, 0.3, 0.9]],
evidence=['Rain', 'Accident'], evidence_card=[2, 2])

model.add_cpds(cpd_rain, cpd_accident, cpd_traffic)


assert model.check_model()

infer = VariableElimination(model)
result = [Link](variables=['Traffic'], evidence={'Rain': 1})
print("Bayesian Network Result:", result)

7. Linear Regression (CSV)

import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from [Link] import mean_squared_error

data = pd.read_csv('your_regression_data.csv') # Replace with your CSV file


print([Link]())

X = [Link][:, :-1]
y = [Link][:, -1]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)


model = LinearRegression()
AI and ML Code Implementations (with CSV + Explanations)

[Link](X_train, y_train)
y_pred = [Link](X_test)
print("MSE:", mean_squared_error(y_test, y_pred))

8. Decision Tree (CSV)

import pandas as pd
from [Link] import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from [Link] import accuracy_score

data = pd.read_csv('your_dataset.csv') # Replace with your CSV file


print([Link]())

X = [Link][:, :-1]
y = [Link][:, -1]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)


model = DecisionTreeClassifier()
[Link](X_train, y_train)
y_pred = [Link](X_test)
print("Decision Tree Accuracy:", accuracy_score(y_test, y_pred))

9. Random Forest (CSV)

import pandas as pd
from [Link] import RandomForestClassifier
from sklearn.model_selection import train_test_split
from [Link] import accuracy_score

data = pd.read_csv('your_dataset.csv') # Replace with your CSV file


print([Link]())

X = [Link][:, :-1]
y = [Link][:, -1]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,


random_state=42)
model = RandomForestClassifier(n_estimators=100)
[Link](X_train, y_train)
y_pred = [Link](X_test)
print("Random Forest Accuracy:", accuracy_score(y_test, y_pred))

You might also like