0% found this document useful (0 votes)
7 views8 pages

Aiml Sem Practicals

Uploaded by

jeevamictian
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)
7 views8 pages

Aiml Sem Practicals

Uploaded by

jeevamictian
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/ 8

1.

Expert Systems(Rule-Based System)


An expert system applies rules to input data to reach conclusions.

PROGRAM:
def expert_system(symptoms):
rules = {
"fever and cough": "You might have the flu.",
"fever and rash": "You might have measles.",
"cough and sore throat": "You might have a cold.",
"fever and headache": "You might have dengue."
}
for condition, diagnosis in rules.items():
if all(symptom in symptoms for symptom in condition.split(" and ")):
return diagnosis
return "No diagnosis found. Consult a doctor."

# Example usage
symptoms = ["fever", "cough"]
print(expert_system(symptoms))

---

2.Decision Tree
A decision tree is a model used to make decisions based on rules.

PPROGRAM:
from sklearn import tree

# Example dataset (features: [outlook, temperature])


# Outlook: 0 = Sunny, 1 = Overcast, 2 = Rainy
# Temperature: 0 = Cool, 1 = Mild, 2 = Hot
X = [[0, 0], [0, 2], [1, 1], [2, 0], [2, 2]] # Training data
y = [0, 0, 1, 1, 0] # Labels (0 = No, 1 = Yes)

# Train a decision tree


clf = tree.DecisionTreeClassifier()
clf = clf.fit(X, y)

# Predict if it's a good day to play sports (outlook: Sunny, temperature:


Hot)
print(clf.predict([[0, 2]])) # Output: [0] (No)

---

3.A* Algorithm
A* finds the shortest path in a graph using a heuristic.

PROGRAM:
from queue import PriorityQueue

def a_star_algorithm(graph, start, goal, heuristic):


pq = PriorityQueue()
pq.put((0, start))
costs = {start: 0}
paths = {start: None}

while not pq.empty():


_, current = pq.get()
if current == goal:
path = []
while current:
path.append(current)
current = paths[current]
return path[::-1]

for neighbor, cost in graph[current]:


new_cost = costs[current] + cost
if neighbor not in costs or new_cost < costs[neighbor]:
costs[neighbor] = new_cost
priority = new_cost + heuristic[neighbor]
pq.put((priority, neighbor))
paths[neighbor] = current

return None

graph = {
'A': [('B', 1), ('C', 4)],
'B': [('D', 1), ('E', 2)],
'C': [('F', 5)],
'D': [('G', 6)],
'E': [('G', 2)],
'F': [('G', 1)],
'G': []
}
heuristic = {'A': 7, 'B': 5, 'C': 8, 'D': 4, 'E': 2, 'F': 1, 'G': 0}

print(a_star_algorithm(graph, 'A', 'G', heuristic))

---

4.Breadth-First Search (BFS)


BFS traverses a graph layer by layer.

PROGRAM:
from collections import deque

def bfs(graph, start):


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

while queue:
node = queue.popleft()
if node not in visited:
visited.add(node)
result.append(node)
queue.extend(graph[node])

return result

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

print(bfs(graph, 'A'))
---

5. **Depth-First Search (DFS)


DFS explores as far as possible along each branch before backtracking.

PROGRAM:
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
result = [start]
for neighbor in graph[start]:
if neighbor not in visited:
result += dfs(graph, neighbor, visited)
return result

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

print(dfs(graph, 'A'))

---

6. Naive Bayes
Naive Bayes is a probabilistic classifier.

PROGRAM:
from sklearn.naive_bayes import GaussianNB

X = [[1, 20], [2, 18], [1, 17], [2, 19]] # Training data (features)
y = [0, 1, 0, 1] # Labels (0 = No, 1 = Yes)

clf = GaussianNB()
clf.fit(X, y)

# Predict outcome for a new input (1 = Female, 21 = Age)


print(clf.predict([[1, 21]]))
```

---

NAIVE BAYES:

import pandas as pd
import re
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score
from sklearn.pipeline import make_pipeline
from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS

# 1. Load the data


def load_data(file_path):
return pd.read_excel(file_path)

# 2. Clean the text


def clean_text(text):
text = text.lower()
text = re.sub(r'[^\w\s]', '', text) # Remove punctuation
words = text.split()
words = [word for word in words if word not in
ENGLISH_STOP_WORDS] # Remove stop words
return ' '.join(words)

# 3. Preprocess the data


def preprocess_data(df):
df['Cleaned_Text'] = df['Review_Text'].apply(clean_text)
X = df['Cleaned_Text']
y = df['Sentiment_Label']
return train_test_split(X, y, test_size=0.2, random_state=42)

# 4. Vectorize the text


def vectorize_text(X_train, X_test):
vectorizer = TfidfVectorizer()
X_train_vec = vectorizer.fit_transform(X_train)
X_test_vec = vectorizer.transform(X_test)
return X_train_vec, X_test_vec, vectorizer

# 5. Train the Naïve Bayes model


def train_naive_bayes(X_train_vec, y_train):
model = MultinomialNB()
model.fit(X_train_vec, y_train)
return model

# 6. Predict sentiment for a new review


def predict_sentiment(model, vectorizer, new_review):
cleaned_review = clean_text(new_review)
review_vec = vectorizer.transform([cleaned_review])
return model.predict(review_vec)[0]

# Main execution
if __name__ == "__main__":
# Load the dataset
file_path = "customer_reviews.xlsx"
data = load_data(file_path)

# Preprocess and split the data


X_train, X_test, y_train, y_test = preprocess_data(data)

# Vectorize the text


X_train_vec, X_test_vec, vectorizer = vectorize_text(X_train, X_test)

# Train the Naïve Bayes model


model = train_naive_bayes(X_train_vec, y_train)

# Evaluate the model


y_pred = model.predict(X_test_vec)
print(f"Model Accuracy: {accuracy_score(y_test, y_pred):.2f}")

# Test the prediction function


new_review = "The delivery was fast, but the product was subpar."
print(f"Review: {new_review}")
print(f"Predicted Sentiment: {predict_sentiment(model, vectorizer,
new_review)}")

MAP COLORING:
def is_safe(node, color, graph, colors):
for neighbor in graph[node]:
if colors[neighbor] == color:
return False
return True

def map_coloring(graph, num_colors, colors, node):


if node == len(graph):
return True

for color in range(1, num_colors + 1):


if is_safe(node, color, graph, colors):
colors[node] = color
if map_coloring(graph, num_colors, colors, node + 1):
return True
colors[node] = 0 # Backtrack

return False

def solve_map_coloring(graph, num_colors):


colors = [0] * len(graph)
if map_coloring(graph, num_colors, colors, 0):
return colors
else:
return "No solution found"

# Example graph as adjacency list


graph = {
0: [1, 2],
1: [0, 2, 3],
2: [0, 1, 3],
3: [1, 2]
}

num_colors = 3
solution = solve_map_coloring(graph, num_colors)
print("Color assignment:", solution)

DEPTH LIMTED SEARCH:

def depth_limited_search(graph, start, goal, limit):


def dls(node, depth):
if depth > limit:
return False
if node == goal:
return True
for neighbor in graph[node]:
if dls(neighbor, depth + 1):
return True
return False

return dls(start, 0)

# Example graph as adjacency list


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

start = 'A'
goal = 'F'
limit = 2

if depth_limited_search(graph, start, goal, limit):


print(f"Path to {goal} found within depth {limit}.")
else:
print(f"No path to {goal} within depth {limit}.")

You might also like