Posts

Showing posts from December, 2024

Lab 8

 Import matplotlib.pyplot as plt From sklearn import datasets From sklearn.model_selection import train_test_split From mlxtend.plotting import plot_decision_regions From sklearn.metrics import accuracy_score From sklearn.ensemble import RandomForestClassifier # Load IRIS data set Iris = datasets.load_iris() X = iris.data[:, 2:] Y = iris.target # Create training/ test data split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1, stratify=y) # Create an instance of Random Forest Classifier Forest = RandomForestClassifier(criterion=’gini’,                                  N_estimators=5,                                  Random_state=1,                                  N_jobs=2) # Fit the model Fo...

Lab 7

 # Step 1: Import Libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn.preprocessing import StandardScaler # Step 2: Load Data # Replace 'your_file.csv' with your dataset file data = pd.read_csv('your_file.csv') # Preview the dataset print(data.head()) # Step 3: Data Preprocessing # Select relevant features for segmentation (example: income and spending score) features = data[['Annual Income (k$)', 'Spending Score (1-100)']] # Scale the data scaler = StandardScaler() scaled_features = scaler.fit_transform(features) # Step 4: Determine the Optimal Number of Clusters inertia = [] K = range(1, 11) for k in K:     kmeans = KMeans(n_clusters=k, random_state=42)     kmeans.fit(scaled_features)     inertia.append(kmeans.inertia_) # Plot the Elbow Curve plt.figure(figsize=(8, 5)) plt.plot(K, inertia, 'bx-') plt.xlabel('Number of Clusters (K)') plt.ylabel('Inertia'...
 Lab 2 For each training example d, do:      If d is positive example          Remove from G any hypothesis h inconsistent with d          For each hypothesis s in S not consistent with d:               Remove s from S               Add to S all minimal generalizations of s consistent with d and having a generalization in G               Remove from S any hypothesis with a more specific h in S      If d is negative example           Remove from S any hypothesis h inconsistent with d           For each hypothesis g in G not consistent with d:                 Remove g from G                 Add to G all minimal specializations of g consistent with d and having a specializati...

Traveling salesman

 from itertools import permutations # Define a graph as a distance matrix graph = [     [0, 10, 15, 20],     [10, 0, 35, 25],     [15, 35, 0, 30],     [20, 25, 30, 0] ] # Number of nodes n = len(graph) # Function to calculate the cost of a path def calculate_path_cost(path, graph):     cost = 0     for i in range(len(path) - 1):         cost += graph[path[i]][path[i + 1]]     cost += graph[path[-1]][path[0]] # Return to the starting point     return cost # Brute force TSP solution def traveling_salesman(graph):     nodes = list(range(n))     min_cost = float('inf')     best_path = None     for perm in permutations(nodes):         cost = calculate_path_cost(perm, graph)         if cost < min_cost:             min_cost = cost             best_p...
  Step 1: Import Libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn.preprocessing import StandardScaler # Step 2: Load Data # Replace 'your_file.csv' with your dataset file data = pd.read_csv('your_file.csv') # Preview the dataset print(data.head()) # Step 3: Data Preprocessing # Select relevant features for segmentation (example: income and spending score) features = data[['Annual Income (k$)', 'Spending Score (1-100)']] # Scale the data scaler = StandardScaler() scaled_features = scaler.fit_transform(features) # Step 4: Determine the Optimal Number of Clusters inertia = [] K = range(1, 11) for k in K:     kmeans = KMeans(n_clusters=k, random_state=42)     kmeans.fit(scaled_features)     inertia.append(kmeans.inertia_) # Plot the Elbow Curve plt.figure(figsize=(8, 5)) plt.plot(K, inertia, 'bx-') plt.xlabel('Number of Clusters (K)') plt.ylabel('Inertia')...
 import pandas as pd from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier, export_text from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, classification_report, confusion_matrix columns = ["Pregnancies", "Glucose", "BloodPressure", "SkinThickness",             "Insulin", "BMI", "DiabetesPedigreeFunction", "Age", "Outcome"] data = pd.read_csv(r"C:\Users\kvadi\Downloads\diabetes.csv", header=1, names=columns) X = data.iloc[:, :-1] y = data.iloc[:, -1] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) model = DecisionTreeClassifier(criterion='entropy', random_state=42) model.fit(X_train, y_train) y_pred = model.predict(X_test) accuracy = accuracy_score(y_test, y_pred) precision = precision_score(y_test, y_pred, zero_division=0) recall = recall_score(y_test, y_pre...

Ai lab 1 2 3 4 5

 s(a,b). s(a,c). s(b,d). s(b,e). s(c,f). s(c,g). s(d,h). s(e,i). s(e,j). s(f,k). goal(f). goal(j). member(X,[X|_]). member(X,[_|Tail]):- member(X,Tail). solve(Node,Solution):- depthfirst([],Node,Solution). depthfirst(Path, Node,[Node | Path]):- goal(Node). depthfirst(Path,Node,Sol):- s(Node,Node1), not(member(Node1,Path)), depthfirst([Node | Path], Node1,Sol). conc([X/L1],L2,[X|L3]):- write('conc'), write(X), write(''), write(L1), write(' '), write(L2), conc(L1,L2,L3). BFS   s(a,b). s(a,c). s(b,d). s(b,e). s(c,f). s(c,g). s(d,h). s(e,i). s(e,j). s(f,k). goal(f). goal(j). solve(Start,Solution):- breadthfirst([[Start]],Solution). breadthfirst([[Node | Path] ].[Node|Path]]) :- goal(Node). breadthfirst([Path | Paths] Solution):- extend(Path,NewPaths), write(NewPaths), nl, conc(Paths,NewPaths, Paths1), breadthfirst(Paths1,Solution). extend([NodePath],NewPaths):- bagof([NewNode, Node | Path),(s(Node, NewNode),not(member(NewNode, [Node | Path]))),NewPaths),!. extend([]...