Posts

Showing posts from January, 2025

Candidate elimination

 def candidate_elimination(data):     G = [["?"] * (len(data[0]) - 1)] # General hypothesis     S = ["0"] * (len(data[0]) - 1) # Specific hypothesis     for instance in data:         x, y = instance[:-1], instance[-1]         if y == "Yes": # Positive example             G = [g for g in G if all(g[i] == "?" or g[i] == x[i] for i in range(len(x)))]             S = [x[i] if s == "0" else s if s == x[i] else "?" for i, s in enumerate(S)]         else: # Negative example             G = [g for g in G for i in range(len(x)) if g[i] == "?" or g[i] != x[i]]     return S, G # Dataset: [Attributes..., Class] data = [["Sunny", "Warm", "Normal", "Strong", "Warm", "Same", "Yes"],         ["Sunny", "Warm", "High", "Strong", "Warm", "Same", "Yes"],         ["Rainy",...

Find s

 # Find-S Algorithm def find_s(data):     hypothesis = ["0"] * len(data[0][:-1]) # Initialize hypothesis     for instance in data:         if instance[-1] == "Yes": # Only consider positive examples             for i in range(len(hypothesis)):                 if hypothesis[i] == "0":                     hypothesis[i] = instance[i]                 elif hypothesis[i] != instance[i]:                     hypothesis[i] = "?"     return hypothesis # Dataset: [Attributes..., Class] dataset = [["Sunny", "Warm", "Normal", "Strong", "Warm", "Same", "Yes"],            ["Sunny", "Warm", "High", "Strong", "Warm", "Same", "Yes"],            ["Rainy", "Cold", "High", "Strong", "Wa...

bayesian network heart disease

 import pandas as pd from sklearn.model_selection import train_test_split from sklearn.naive_bayes import GaussianNB from sklearn.metrics import accuracy_score data = pd.read_csv("heart.csv") # Load dataset (ensure heart.csv is available) X, y = data.iloc[:, :-1], data.iloc[:, -1] # Features and target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) model = GaussianNB().fit(X_train, y_train) # Train Naive Bayes model y_pred = model.predict(X_test) # Predict on test data print("Accuracy:", accuracy_score(y_test, y_pred)) sample = [[57, 1, 2, 130, 236, 0, 0, 174, 0, 0.0, 1, 1, 3]] # Example input print("Diagnosis:", "Heart Disease" if model.predict(sample)[0] else "No Heart Disease")

C4.5

 from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score from sklearn.model_selection import train_test_split import pandas as pd data = pd.read_csv("heart.csv") # Load dataset (ensure heart.csv is available) X, y = data.iloc[:, :-1], data.iloc[:, -1] # Features and target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) model = DecisionTreeClassifier(criterion="entropy").fit(X_train, y_train) # C4.5 uses entropy y_pred = model.predict(X_test) print("Accuracy:", accuracy_score(y_test, y_pred), "Precision:", precision_score(y_test, y_pred),       "Recall:", recall_score(y_test, y_pred), "F1 Score:", f1_score(y_test, y_pred))

Kmeans clustering

 from sklearn.cluster import KMeans import matplotlib.pyplot as plt import pandas as pd data = pd.read_csv("data.csv") # Load dataset (ensure data.csv is available) X = data.iloc[:, :].values # Use all columns as features kmeans = KMeans(n_clusters=3, random_state=42).fit(X) # Apply K-Means with 3 clusters labels = kmeans.labels_ # Cluster labels for each data point plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis') # Visualize clusters plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], color='red', marker='x') # Centers plt.title("K-Means Clustering") plt.show()

Random forest

 from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split import pandas as pd data = pd.read_csv("heart.csv") # Load dataset (ensure heart.csv is available) X, y = data.iloc[:, :-1], data.iloc[:, -1] # Features and target 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, random_state=42).fit(X_train, y_train) y_pred = model.predict(X_test) print("Accuracy:", accuracy_score(y_test, y_pred)) # Print accuracy

Best first search

 import heapq def best_first_search(graph, start, goal):     pq = [(0, start)] # Priority queue (cost, node)     visited = set() # Track visited nodes     while pq:         cost, node = heapq.heappop(pq)         if node in visited:             continue         visited.add(node)         if node == goal:             return f"Goal {goal} reached with cost {cost}"         for neighbor, weight in graph[node]:             if neighbor not in visited:                 heapq.heappush(pq, (weight, neighbor))     return "Goal not reachable" graph = {     'A': [('B', 1), ('C', 4)],     'B': [('D', 2), ('E', 5)],     'C': [('F', 1)],     'D': [], 'E': [], 'F': [] } print(best_first_searc...

TSP

 from itertools import permutations def tsp(graph, start):     nodes = list(graph.keys())     nodes.remove(start)     min_cost, best_path = float('inf'), []          for perm in permutations(nodes):         path = [start] + list(perm) + [start]         cost = sum(graph[path[i]][path[i+1]] for i in range(len(path) - 1))         if cost < min_cost:             min_cost, best_path = cost, path          return best_path, min_cost graph = {     'A': {'B': 10, 'C': 15, 'D': 20},     'B': {'A': 10, 'C': 35, 'D': 25},     'C': {'A': 15, 'B': 35, 'D': 30},     'D': {'A': 20, 'B': 25, 'C': 30} } print(tsp(graph, 'A'))  Traveling salesman

N puzzle

 import heapq def heuristic(state, goal):     return sum(abs(s % 3 - g % 3) + abs(s // 3 - g // 3) for s, g in zip(state, goal) if s) def get_neighbors(state):     i = state.index(0)     moves = [(i-3, i), (i+3, i), (i-1, i), (i+1, i)]     neighbors = []     for new, old in moves:         if 0 <= new < 9 and not (i % 3 == 0 and old % 3 == 2) and not (i % 3 == 2 and old % 3 == 0):             new_state = list(state)             new_state[old], new_state[new] = new_state[new], new_state[old]             neighbors.append(tuple(new_state))     return neighbors def a_star(start, goal):     pq, visited = [(0 + heuristic(start, goal), 0, start)], set()     while pq:         _, cost, state = heapq.heappop(pq)         if state in visited: continue   ...

N queens

 def solve_n_queens(n, board=[], col=0):     if col == n:         print_board(board, n) # Print solution         return     for row in range(n):         if all(abs(row - r) != abs(col - c) and row != r for c, r in enumerate(board)):             solve_n_queens(n, board + [row], col + 1) def print_board(board, n):     for row in board:         print("".join("Q" if i == row else "." for i in range(n)))     print("\n") n = 8 # Example for 8-Queens solve_n_queens(n)