EXP 1
def print_board(positions, n):
for r in range(n):
for c in range(n):
if positions[r] == c:
print("Q", end=" ")
else:
print(".", end=" ")
print()
print()
def solve_nqueens(row, n, positions, cols, diag1, diag2, solutions):
if row == n:
[Link](positions[:])
return
for c in range(n):
d1 = row - c + n - 1
d2 = row + c
if not cols[c] and not diag1[d1] and not diag2[d2]:
positions[row] = c
cols[c] = diag1[d1] = diag2[d2] = True
solve_nqueens(row + 1, n, positions, cols, diag1, diag2, solutions)
cols[c] = diag1[d1] = diag2[d2] = False
def main():
n = int(input("Enter number of queens: "))
positions = [-1] * n
cols = [False] * n
diag1 = [False] * (2 * n - 1)
diag2 = [False] * (2 * n - 1)
solutions = []
solve_nqueens(0, n, positions, cols, diag1, diag2, solutions)
print("\nTotal solutions:", len(solutions))
print()
for i, sol in enumerate(solutions, 1):
print("Solution {}:".format(i))
print_board(sol, n)
if __name__ == "__main__":
main()
EXP 2
def iterative_dfs(graph, start):
visited = []
stack = [start]
while stack:
node = [Link]()
if node not in visited:
[Link](node)
# Add neighbors in reverse order to maintain DFS order
for neighbor in reversed(graph[node]):
if neighbor not in visited:
[Link](neighbor)
return visited
if __name__ == "__main__":
# Graph as adjacency list
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
traversal = iterative_dfs(graph, 'A')
print("DFS Traversal (Iterative):", traversal)
EXP 3
import networkx as nx
import [Link] as plt
import heapq
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B', 'G'],
'E': ['B', 'G'],
'F': ['C', 'G'],
'G': ['D', 'E', 'F']
}
heuristic = {
'A': 7,
'B': 6,
'C': 8,
'D': 3,
'E': 4,
'F': 4,
'G': 0
}
def greedy_best_first_search(start, goal):
visited = set()
pq = []
[Link](pq, (heuristic[start], [start])) # (heuristic, path)
while pq:
_, path = [Link](pq)
node = path[-1]
if node == goal:
return path
if node not in visited:
[Link](node)
for neighbor in graph[node]:
if neighbor not in visited:
new_path = list(path)
new_path.append(neighbor)
[Link](pq, (heuristic[neighbor], new_path))
return None
start_node = 'A'
goal_node = 'G'
path = greedy_best_first_search(start_node, goal_node)
print("Path found:", " -> ".join(path))
G = [Link]()
for node in graph:
for neighbor in graph[node]:
G.add_edge(node, neighbor)
pos = nx.spring_layout(G)
[Link](G, pos, with_labels=True, node_color='skyblue', node_size=1500, font_size=12)
path_edges = list(zip(path, path[1:]))
nx.draw_networkx_edges(G, pos, edgelist=path_edges, edge_color='r', width=2)
[Link]()
EXP 4
def alphabeta(node, depth, alpha, beta, maximizingPlayer, values):
if depth == 0 or node >= len(values):
return values[node]
if maximizingPlayer:
value = float('-inf')
for i in range(2): # two child nodes
value = max(value, alphabeta(node * 2 + i + 1, depth - 1, alpha, beta, False, values))
alpha = max(alpha, value)
if alpha >= beta:
break # Beta cut-off
return value
else:
value = float('inf')
for i in range(2):
value = min(value, alphabeta(node * 2 + i + 1, depth - 1, alpha, beta, True, values))
beta = min(beta, value)
if beta <= alpha:
break # Alpha cut-off
return value
values = [3, 5, 6, 9, 1, 2, 0, -1]
result = alphabeta(3, 0, float('-inf'), float('inf'), True, values)
print("Alpha-Beta value from node=3:", result)
print("=== Code Execution Successful ===")
EXP 5
import random
def objective_function(x):
return -x**2 + 10
def hill_climbing():
current_solution = [Link](-10, 10)
print("Hill Climbing start:", current_solution)
current_value = objective_function(current_solution)
while True:
neighbors = [current_solution - 1, current_solution + 1]
neighbor_values = [objective_function(n) for n in neighbors]
best_neighbor_value = max(neighbor_values)
best_neighbor = neighbors[neighbor_values.index(best_neighbor_value)]
if best_neighbor_value <= current_value:
break
current_solution, current_value = best_neighbor, best_neighbor_value
print("Best solution found:", current_solution, "with value:", current_value)
print("\n=== Code Execution Successful ===")
hill_climbing()
EXP 6
def map_coloring(graph, colors):
def is_valid(color_assignment, region, color):
for adjacent_region in graph[region]:
if adjacent_region in color_assignment and color_assignment[adjacent_region] ==
color:
return False
return True
def backtrack(color_assignment, regions): if
len(color_assignment) == len(regions):
return color_assignment
for region in regions:
if region not in color_assignment:
for color in colors:
if is_valid(color_assignment, region, color):
color_assignment[region] = color
result = backtrack(color_assignment, regions) if
result:
return result
del color_assignment[region]
return None
return None
regions = list([Link]())
return backtrack({}, regions)
# Example usage:
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
colors = ['red', 'green', 'blue']
solution = map_coloring(graph, colors)
print(solution)
EXP 7
from collections import defaultdict def
topological_sort(graph, vertices):
visited = [False] * vertices
stack = []
def dfs(v):
visited[v] =
True
for neighbor, _ in graph[v]:
if not visited[neighbor]:
dfs(neighbor)
[Link](v)
for i in
range(vertices): if
not visited[i]:
dfs(i)
[Link]()
return stack
def shortest_path_dag(graph, vertices, start): topological_order =
topological_sort(graph, vertices) distances = [float('inf')] *
vertices
distances[start] = 0
for node in topological_order:
if distances[node] != float('inf'):
for neighbor, weight in graph[node]:
if distances[node] + weight < distances[neighbor]:
distances[neighbor] = distances[node] + weight
return distances
graph = defaultdict(list)
graph[0].append((1, 2))
graph[0].append((4, 1))
graph[1].append((2, 3))
graph[1].append((4, 2))
graph[2].append((3, 6))
graph[4].append((2, 2))
graph[4].append((5, 4))
graph[5].append((3, 1))
vertices = 6
start_node = 0
shortest_distances = shortest_path_dag(graph, vertices, start_node) print("Shortest distances
from node", start_node, ":", shortest_distances)
EXP 8
Class
ExpertSystem:
def init
(self):
self.knowledge_base = []
def add_rule(self, condition, diagnosis):
self.knowledge_base.append((condition, diagnosis))
def diagnose(self, patient_data):
for condition, diagnosis in self.knowledge_base: if
condition(patient_data):
return diagnosis
return “Unknown Condition”
# Example conditions (rules) def
has_pneumonia(patient):
return ([Link](‘fever’) and
[Link](‘cough’) and
[Link](‘difficulty_breathing’))
def has_measles(patient):
return ([Link](‘fever’)
and [Link](‘rash’))
def has_strep_throat(patient): return
([Link](‘fever’) and
[Link](‘sore_throat’))
# Initialize expert system
expert_system = ExpertSystem()
# Add rules to the knowledge base expert_system.add_rule(has_pneumonia,
“Pneumonia”) expert_system.add_rule(has_measles, “Measles”)
expert_system.add_rule(has_strep_throat, “Strep Throat”)
def get_patient_data():
print(“Please answer the following questions with ‘yes’ or ‘no’:”)
fever = input(“Does the patient have a fever? “).strip().lower() == ‘yes’ cough =
input(“Does the patient have a cough? “).strip().lower() == ‘yes’ difficulty_breathing =
input(“Does the patient have difficulty breathing?
“).strip().lower() == ‘yes’
rash = input(“Does the patient have a rash? “).strip().lower() == ‘yes’ sore_throat =
input(“Does the patient have a sore throat? “).strip().lower() ==
‘yes’
return {
‘fever’: fever,
‘cough’: cough,
‘difficulty_breathing’: difficulty_breathing,
‘rash’: rash,
‘sore_throat’: sore_throat
}
patient_data = get_patient_data()
diagnosis = expert_system.diagnose(patient_data)
print(f”Diagnosis: {diagnosis}”)
EXP 9
import heapq
# Define a task as a tuple (priority, task_name) tasks =
[
(2, "Task A"), # Lower number means higher priority (1,
"Task B"),
(3, "Task C"),
(5, "Task D"),
]
def schedule_tasks(tasks):
# Use a min-heap to schedule tasks based on priority
[Link](tasks) # Transform the list into a heap
scheduled_tasks = []
while tasks:
# Pop the task with the highest priority (lowest number) priority, task =
[Link](tasks) scheduled_tasks.append(task)
return scheduled_tasks
# Generate the task schedule
task_schedule = schedule_tasks(tasks)
# Output the scheduled tasks print("Scheduled Tasks (in order):") for task in task_schedule:
print(task)
EXP 10
import numpy as np
import [Link] as plt
# Given data
training_hours = [Link]([1, 2, 3, 4, 5])
performance_scores = [Link]([50, 55, 60, 65, 70])
# Number of data points n =
len(training_hours)
# Calculating the sums required for the formulas sum_x =
[Link](training_hours)
sum_y = [Link](performance_scores)
sum_xy = [Link](training_hours * performance_scores) sum_x_squared =
[Link](training_hours ** 2)
# Calculating the slope (m) and intercept (b)
m = (n * sum_xy - sum_x * sum_y) / (n * sum_x_squared - sum_x ** 2)
b = (sum_y * sum_x_squared - sum_x * sum_xy) / (n * sum_x_squared - sum_x
** 2)
# Equation of the best-fit line best_fit_line =
m * training_hours + b
# Plotting the data points and the best-fit line
[Link](figsize=(8, 6))
[Link](training_hours, performance_scores, color='blue', label='Data Points')
[Link](training_hours, best_fit_line, color='red', label=f'Best-Fit Line: y =
{m:.1f}x + {b:.1f}')
[Link]('Training Hours') [Link]('Performance
Scores') [Link]('Training Hours vs. Performance
Scores') [Link]()
[Link](True)
[Link]()
EXP 12
import pandas as pd
from [Link] import KNeighborsClassifier import
numpy as np
# Create the dataset
data = {
'Amount Spent': [500, 150, 200, 700, 50, 100, 600, 250],
'Frequency': [10, 5, 2, 8, 3, 6, 7, 4],
'Types of Products': [2, 1, 1, 2, 0, 0, 2, 1],
'Segment': ['High-Value', 'Frequent', 'Occasional', 'High-Value', 'Occasional',
'Frequent', 'High-Value', 'Occasional']}
df = [Link](data)
# Define features and labels
X = df[['Amount Spent', 'Frequency', 'Types of Products']] y =
df['Segment']
# Initialize the k-NN classifier k = 3
knn = KNeighborsClassifier(n_neighbors=k) # Fit
the model
[Link](X, y)
# New Data Point
new_data = [Link]([[300, 5, 1]])
# Predict the segment for the new data point
predicted_segment = [Link](new_data)[0] #
Output the results
print("Dataset with Segments:")
print(df)
print("\nPredicted Segment for New Data Point (Amount Spent: 300, Frequency: 5, Types of
Products: 1):", predicted_segment)
EXP 13
# Import necessary libraries
import numpy as np
import pandas as pd # type: ignore
from sklearn.feature_extraction.text import CountVectorizer from
sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from [Link] import accuracy_score, classification_report, confusion_matrix
# Data
data =
{ 'Email':
[
'Win a free iPhone!',
'Your account has been compromised.', 'Limited
time offer!',
'Hello, how are you?', 'You
won a prize!', 'Your
payment is due.', 'Free trial
offer!', 'Hello, what\'s up?',
'Click here to win!',
'Your account is secure.'
],
'Label': ['Spam', 'Spam', 'Spam', 'Not Spam', 'Spam', 'Not Spam', 'Spam', 'Not Spam', 'Spam',
'Not Spam']
}
# Convert data to DataFrame df
= [Link](data)
# Split data into training and testing sets X =
df['Email']
y = df['Label']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Create bag-of-words representation
vectorizer = CountVectorizer()
X_train_count = vectorizer.fit_transform(X_train) X_test_count =
[Link](X_test)
# Create Naive Bayes classifier clf
= MultinomialNB()
# Train classifier
[Link](X_train_count, y_train) #
Predict spam/Not Spam
y_pred = [Link](X_test_count) #
Evaluate classifier
print("Accuracy:", accuracy_score(y_test, y_pred)) print("Classification
Report:\n", classification_report(y_test, y_pred)) print("Confusion Matrix:\n",
confusion_matrix(y_test, y_pred))
# Test with new email new_email =
['You won a prize!']
new_email_count = [Link](new_email) predicted_label =
[Link](new_email_count) print("Predicted Label:",
predicted_label)
EXP 14
import pandas as pd
from sklearn.model_selection import train_test_split from
[Link] import DecisionTreeClassifier from sklearn
import tree
import [Link] as plt #
Step 1: Create the dataset data = {
'Outlook': ['Sunny', 'Sunny', 'Overcast', 'Rainy', 'Rainy', 'Rainy', 'Overcast',
'Sunny', 'Sunny', 'Rainy', 'Sunny', 'Overcast', 'Overcast', 'Rainy'],
'Temperature': ['Hot', 'Hot', 'Hot', 'Mild', 'Cool', 'Cool', 'Cool',
'Mild', 'Cool', 'Mild', 'Mild', 'Hot', 'Mild', 'Mild'],
'Humidity': ['High', 'High', 'High', 'High', 'Normal', 'Normal', 'Normal',
'High', 'Normal', 'Normal', 'Normal', 'Normal', 'High', 'High'], 'Windy': [False,
True, False, False, False, True, True,
False, False, False, True, False, True, True],
'Play Tennis': ['No', 'No', 'Yes', 'Yes', 'Yes', 'No', 'Yes',
'No', 'Yes', 'Yes', 'Yes', 'Yes', 'Yes', 'No']
}
# Convert to DataFrame df
= [Link](data)
# Step 2: Preprocess the data (Encoding categorical variables)
df_encoded = pd.get_dummies(df, columns=['Outlook', 'Temperature', 'Humidity'],
drop_first=True)
# Step 3: Define features and target variable X =
df_encoded.drop('Play Tennis', axis=1)
y = df_encoded['Play Tennis'].map({'Yes': 1, 'No': 0}) # Step
4: Split the data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Step 5: Train the Decision Tree Classifier
clf = DecisionTreeClassifier(random_state=42)
[Link](X_train, y_train)
# Step 6: Evaluate the model accuracy =
[Link](X_test, y_test) print(f'Accuracy:
{accuracy:.2f}')
# Optional: Visualize the Decision Tree
[Link](figsize=(10, 8))
tree.plot_tree(clf, feature_names=[Link], class_names=['No', 'Yes'], filled=True)
[Link]('Decision Tree for Playing Tennis') [Link]()
EXP 15
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer from
[Link] import RandomForestClassifier
from [Link] import classification_report, accuracy_score #
Sample Dataset
data = [Link]({
'review': ["I love this product", "This is terrible", "Not bad", "Could be better", "Absolutely
amazing!"],
'sentiment': ['positive', 'negative', 'neutral', 'neutral', 'positive']
})
# Data Preprocessing
X = data['review'] # Features (Text Data)
y = data['sentiment'] # Target (Sentiment Class)
# Convert text data into numeric features using TF-IDF tfidf =
TfidfVectorizer(stop_words='english')
X_tfidf = tfidf.fit_transform(X)
# Split the dataset into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X_tfidf, y, test_size=0.2, random_state=42)
# Model Training using Random Forest
rf_classifier = RandomForestClassifier(n_estimators=100, random_state=42)
rf_classifier.fit(X_train, y_train)
# Predictions
y_pred = rf_classifier.predict(X_test)
# Check unique classes in y_test and update target_names accordingly unique_classes =
y_train.unique()
print(f"Unique classes in training data: {unique_classes}")
# Define the classification report's target names dynamically based on unique classes
if len(unique_classes) == 2:
target_names = ['negative', 'positive'] # Adjust if neutral is included in 2-class case
elif len(unique_classes) == 3:
target_names = ['negative', 'neutral', 'positive'] #
Evaluate Model Performance
accuracy = accuracy_score(y_test, y_pred)
report = classification_report(y_test, y_pred, target_names=target_names) print(f"Accuracy:
{accuracy * 100:.2f}%")
print("Classification Report:\n", report)
EXP 16
import numpy as np
import pandas as pd
import [Link] as plt
from [Link] import KMeans
from [Link] import StandardScaler from
[Link] import PCA
# Generate synthetic health and fitness data
[Link](0)
num_users = 100
data = {
'daily_steps': [Link](7000, num_users) + [Link](0, 1500,
num_users),
'calories_burned': [Link](300, num_users) + [Link](0, 50,
num_users),
'workout_type': [Link](['Cardio', 'Strength', 'Yoga', 'HIIT'],
num_users)
}
df = [Link](data)
df['workout_type'] = df['workout_type'].astype('category').[Link] # Convert workout
types to numeric codes
# Standardize the data
features = df[['daily_steps', 'calories_burned', 'workout_type']] scaler =
StandardScaler()
features_scaled = scaler.fit_transform(features) #
Apply K-means clustering
kmeans = KMeans(n_clusters=3, random_state=0)
df['cluster'] = kmeans.fit_predict(features_scaled) #
Visualizing the clusters using PCA
pca = PCA(n_components=2)
features_pca = pca.fit_transform(features_scaled)
[Link](figsize=(10, 6))
[Link](features_pca[:, 0], features_pca[:, 1], c=df['cluster'], cmap='viridis', marker='o')
centers_pca = [Link](kmeans.cluster_centers_) [Link](centers_pca[:, 0],
centers_pca[:, 1], c='red', marker='X', s=200, label='Centroids')
[Link]('K-means Clustering of Health and Fitness Data') [Link]('PCA
Feature 1')
[Link]('PCA Feature 2')
[Link]()
[Link]()
[Link]()
# Display cluster centers
cluster_centers = scaler.inverse_transform(kmeans.cluster_centers_)
cluster_df = [Link](cluster_centers, columns=['daily_steps',
'calories_burned', 'workout_type'])
cluster_df['workout_type'] = ['Cardio', 'Strength', 'Yoga'] # Assigning
representative workout types for the example
print("Cluster Centers:\n", cluster_df)
EXP 17
import numpy as np
from [Link] import KMeans
from [Link] import pairwise_distances from
[Link] import make_blobs
from [Link] import euclidean, cosine def
custom_kmeans(X, n_clusters, metric='euclidean'):
if metric == 'euclidean':
distance_metric = euclidean
elif metric == 'cosine':
distance_metric =
cosine
else:
raise ValueError("Unsupported metric")
centroids = X[[Link]([Link][0], n_clusters, replace=False)] prev_centroids =
np.zeros_like(centroids)
labels = [Link]([Link][0])
while not [Link](centroids == prev_centroids):
prev_centroids = [Link]()
distances = [Link]([[distance_metric(x, c) for c in centroids] for x in X]) labels =
[Link](distances, axis=1)
for i in range(n_clusters):
cluster_points = X[labels == i]
if len(cluster_points) > 0:
centroids[i] = cluster_points.mean(axis=0)
return centroids, labels
X, y = make_blobs(n_samples=300, centers=4, cluster_std=0.60, random_state=0)
centroids, labels = custom_kmeans(X, n_clusters=4, metric='euclidean') print("Centroids:",
centroids)
print("Labels:", labels
EXP 18
import pandas as pd
import numpy as np
from [Link] import PCA
from sklearn.model_selection import train_test_split from
[Link] import RandomForestClassifier
from [Link] import accuracy_score, classification_report from
[Link] import StandardScaler
import [Link] as plt
# Sample synthetic data (replace with actual dataset) data =
{
'income': [50000, 60000, 35000, 80000, 45000, 90000, 75000, 30000, 62000,
100000],
'debt': [5000, 10000, 2000, 5000, 7000, 12000, 6000, 1500, 9000, 11000],
'credit_history': [10, 20, 5, 15, 12, 25, 18, 6, 22, 28],
'spending_score': [50, 70, 30, 80, 40, 90, 65, 25, 60, 85],
'loan_amount': [20000, 15000, 8000, 25000, 12000, 30000, 17000, 7000, 14000,
26000],
'risk': [0, 1, 0, 1, 0, 1, 0, 0, 1, 1] # 0 = Low Risk, 1 = High Risk
}
df = [Link](data)# Split features and target X =
[Link]('risk', axis=1)
y = df['risk']
# Standardize the data
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Perform PCA to reduce dimensionality
pca = PCA(n_components=2) # Reduce to 2 components for visualization X_pca =
pca.fit_transform(X_scaled)
# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X_pca, y, test_size=0.3, random_state=42)
# Train a classifier (e.g., Random Forest) on the PCA-reduced data model =
RandomForestClassifier(random_state=42) [Link](X_train, y_train)
# Make predictions and evaluate the model y_pred =
[Link](X_test)
accuracy = accuracy_score(y_test,
y_pred) report =
classification_report(y_test, y_pred) #
Print the results print(f"Accuracy:
{accuracy:.2f}")
print("\nClassification Report:\n", report) #
Visualize the PCA components
[Link](figsize=(8, 6))
[Link](X_pca[:, 0], X_pca[:, 1], c=y, cmap='viridis', edgecolor='k', s=100)
[Link]('Principal Component 1')
[Link]('Principal Component 2')
[Link]('PCA of Credit Risk Dataset')
[Link](label='Risk Level')
[Link]()
EXP 19
from collections import defaultdict def
apriori(transactions, min_support):
item_counts = defaultdict(int) for
transaction in transactions:
for item in transaction:
item_counts[item] += 1
frequent_1_itemsets = [item for item, count in item_counts.items() if count >= min_support]
frequent_itemsets = [(item, count) for item, count in item_counts.items() if count >=
min_support]
k=2
while frequent_1_itemsets:
candidate_itemsets = generate_candidate_itemsets(frequent_1_itemsets, k) candidate_counts =
defaultdict(int)
for transaction in transactions:
for candidate in candidate_itemsets:
if set(candidate).issubset(transaction):
candidate_counts[tuple(sorted(candidate))] += 1
frequent_k_itemsets = [
(list(itemset), count) for itemset, count in candidate_counts.items() if count >= min_support
]
frequent_itemsets.extend(frequent_k_itemsets)
frequent_1_itemsets = [itemset[0] for itemset, count in frequent_k_itemsets] k += 1
return frequent_itemsets
def generate_candidate_itemsets(frequent_itemsets, k):
candidate_itemsets = []
n = len(frequent_itemsets)
for i in range(n):
for j in range(i + 1, n):
if frequent_itemsets[i][:k-2] == frequent_itemsets[j][:k-2]:
candidate = sorted(list(set(frequent_itemsets[i] + frequent_itemsets[j]))) if
len(candidate) == k:
candidate_itemsets.append(candidate)
return candidate_itemsets
# Example Usage
transactions = [ ['A',
'B', 'C'],
['A', 'D'],
['B', 'C', 'E'],
['A', 'B', 'C', 'D'],
['A', 'B', 'E'] ]
min_support = 2
frequent_itemsets = apriori(transactions, min_support)
print("Frequent Itemsets:")
for itemset, support in frequent_itemsets:
print(f"{itemset}: {support}")
EXP 20
from collections import defaultdict def
eclat(transactions, min_support):
vertical_db = defaultdict(set)
for i, transaction in enumerate(transactions):
for item in transaction:
vertical_db[item].add(i)
frequent_itemsets = {}
def recursive_eclat(itemsets, tid_sets):
for itemset, tids in tid_sets.items():
support = len(tids)
if support >= min_support:
frequent_itemsets[itemset] = support
new_tid_sets = {}
for item in vertical_db:
if item not in itemset:
new_tids = [Link](vertical_db[item]) #Efficient intersection if
len(new_tids)>0:
new_itemset = tuple(sorted(list(itemset) + [item]))
new_tid_sets[new_itemset] = new_tids recursive_eclat(itemset,
new_tid_sets)
initial_tid_sets = { (item,): tids for item, tids in vertical_db.items() } recursive_eclat((),
initial_tid_sets)
return frequent_itemsets
transactions = [
['A', 'B', 'C'],
['A', 'D'], ['B', 'C', 'E'],
['A', 'B', 'C', 'D'],
['A', 'B', 'E']
]
min_support = 2
frequent_itemsets = eclat(transactions, min_support) print("Frequent
Itemsets:")
for itemset, support in frequent_itemsets.items():
print(f"{itemset}: {support}")
EXP 21
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split from
[Link] import StandardScaler from
sklearn.linear_model import LogisticRegression
from [Link] import confusion_matrix, classification_report, accuracy_score
# Create synthetic dataset (replace with real data)
# Features: transaction amount, merchant category, geographical location, etc. data = {
'Transaction_Amount': [100, 150, 200, 250, 300, 500, 50, 10000, 120, 130],
'Merchant_Category': ['Groceries', 'Electronics', 'Groceries', 'Clothing', 'Electronics',
'Luxury', 'Groceries', 'Luxury', 'Groceries', 'Electronics'], 'Geographical_Location': ['New
York', 'California', 'New York', 'Texas', 'California',
'New York', 'Texas', 'California', 'New York', 'Texas'],
'Fraudulent': [0, 0, 0, 0, 0, 1, 0, 1, 0, 0] # 1 = Fraud, 0 = Legitimate
}
df = [Link](data) #
Display the dataset
print("Dataset:\n", df)
# Encode categorical variables
df_encoded = pd.get_dummies(df, columns=['Merchant_Category', 'Geographical_Location'],
drop_first=True)
# Split data into features and target
X = df_encoded.drop('Fraudulent', axis=1) y =
df_encoded['Fraudulent']
# Split into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Standardize the features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = [Link](X_test)
# Train a logistic regression model model = LogisticRegression() [Link](X_train_scaled,
y_train) # Make predictions
y_pred = [Link](X_test_scaled) #
Evaluate the model
accuracy = accuracy_score(y_test, y_pred) conf_matrix =
confusion_matrix(y_test, y_pred) class_report =
classification_report(y_test, y_pred) # Print the results
print(f"\nModel Accuracy: {accuracy:.2f}") print("\
nConfusion Matrix:\n", conf_matrix) print("\
nClassification Report:\n", class_report)
EXP 22
import numpy as np
import [Link] as plt
# Simulated treatment effectiveness
true_effectiveness = [0.1, 0.5, 0.8] # True effectiveness rates for treatments A,
B, and C
class TreatmentRecommendationSystem:
def _init_(self, n_treatments):
self.n_treatments = n_treatments
self.q_values = [Link](n_treatments) # Estimated effectiveness for each treatment
self.action_counts = [Link](n_treatments) # Counts of how many times each treatment was
chosen
self.total_reward = 0 # Total reward (effectiveness) received def
select_treatment(self, exploration_prob):
"""Select treatment using epsilon-greedy strategy.""" if
[Link]() < exploration_prob:
return [Link](self.n_treatments) # Explore else:
return [Link](self.q_values) # Exploit def
update_q_values(self, treatment, reward):
"""Update Q-values based on received reward.""" self.action_counts[treatment]
+= 1
# Incrementally update the estimated effectiveness
self.q_values[treatment] += (reward - self.q_values[treatment]) / self.action_counts[treatment]
self.total_reward += reward #
Parameters
n_episodes = 1000 exploration_prob = 1.0
decay_rate = 0.99
# Instantiate the recommendation system
recommendation_system =
TreatmentRecommendationSystem(n_treatments=len(true_effectiveness)) rewards = []
for episode in range(n_episodes):
# Select treatment for the current episode
treatment = recommendation_system.select_treatment(exploration_prob) # Simulate
patient outcome based on the selected treatment
outcome = [Link]() < true_effectiveness[treatment] # Outcome is True with the
treatment's effectiveness
reward = 1 if outcome else 0 # Reward is 1 for a positive outcome, 0 otherwise # Update
the recommendation system with the received reward
recommendation_system.update_q_values(treatment, reward)
# Store the total reward for analysis
[Link](recommendation_system.total_reward)
# Decay exploration probability
exploration_prob = max(0.1, exploration_prob * decay_rate) # Plotting
the results
[Link](rewards) [Link]('Episodes')
[Link]('Total Rewards')
[Link]('Total Rewards Over Episodes for Personalized Treatment Recommendations')
[Link]()
[Link]()
EXP 23
import numpy as np
import pandas as pd
from [Link] import Tokenizer from
[Link] import pad_sequences
from [Link] import Model
from [Link] import Input, Dense, Embedding, LSTM,
Concatenate, Flatten, Conv2D, MaxPooling2D data
={
'review': ['Great movie!', 'Not good', 'Fantastic!', 'Boring', 'Loved it!', 'Hated it!'], 'label': [1, 0, 1,
0, 1, 0]
}
df = [Link](data)
max_words = 1000
max_len = 20
tokenizer = Tokenizer(num_words=max_words)
tokenizer.fit_on_texts(df['review'])
sequences = tokenizer.texts_to_sequences(df['review']) X_text =
pad_sequences(sequences, maxlen=max_len) num_samples =
len(df)
image_shape = (100, 100, 3)
X_images = [Link](num_samples, *image_shape)
text_input = Input(shape=(max_len,), name="text_input")
text_embedding = Embedding(input_dim=max_words, output_dim=128)(text_input)
text_lstm = LSTM(64)(text_embedding)
image_input = Input(shape=image_shape, name="image_input") x =
Conv2D(32, (3, 3), activation='relu')(image_input)
x = MaxPooling2D((2, 2))(x) x
= Flatten()(x)
combined = Concatenate()([text_lstm, x])
output = Dense(1, activation='sigmoid')(combined)
model = Model(inputs=[text_input, image_input], outputs=output)
[Link](optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
[Link]([X_text, X_images], df['label'].values, epochs=10, batch_size=2) loss,
accuracy = [Link]([X_text, X_images], df['label'].values) print(f"Model
accuracy: {accuracy}")
predictions = [Link]([X_text, X_images])
print("Predictions:", predictions)