AI&ML
AI&ML
Aim:
To write a python program for implement Breadth First Search (BFS)
Algorithm:
Step 1: Create a function bfs
Step 2: In the function perform bfs
Step 3: Get the graph and node as a input from the user
Step 4: Assign visited =[]
Step 5: Assign queue=[]
Step 6: Call the function
Program:
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
while queue:
s = queue.pop(0)
print (s, end = " ")
# Driver Code
bfs(visited, graph, 'A')
Result:
Thus the program for python Implementation BFS is executed and the output is
obtained.
Aim:
To write a python program for Implementation Depth First Search (DFS)
Algorithm:
Step 1: Create a function dfs
Step 2: In the function perform dfs
Step 3: Get the graph and node as a input from the user
Step 4: Assign dfs()
Step 5: Call the function
Program:
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = set() # Set to keep track of visited nodes of graph.
def dfs(visited, graph, node): #function for dfs
if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
print("Following is the Depth-First Search")
dfs(visited, graph, '5')
Result:
Thus the program for python Implementation DFS is executed and the output is
obtained.
Aim:
To write a python program to perform the A* algorithm.
Algorithm:
Step 2: check if the open node is empty or not if the list is empty return failure and
stop
Step 4: select the node from the user while it has the smallest value
Step 5: expand node A and generate all of its successor and put into closed list
Step 6: else if node n is already open and closed then H should be attached to the back
Program:
import heapq
def aStarAlgo(start_node, stop_node):
open_heap = [(0, start_node)]
closed_set = set()
g = {}
parents = {}
g[start_node] = 0
parents[start_node] = start_node
while len(open_heap) > 0:
(f, n) = heapq.heappop(open_heap)
if n == stop_node or Graph_nodes[n] is None:
pass
def get_neighbors(v):
if v in Graph_nodes:
return Graph_nodes[v]
else:
return None
def heuristic(n):
H_dist = {'A': 11, 'B': 6, 'C': 99, 'D': 1, 'E': 7, 'G': 0}
return H_dist[n]
Graph_nodes = {
'A': [('B', 2), ('E', 3)],
'B': [('A', 2), ('C', 1), ('G', 9)],
'C': [('B', 1)],
Output:-
Result:
Thus, the python program for implementation of A * algorithm was executed and its
output is verified successfully.
Aim:
To write a python program to implement the memory-bounded A*.
Algorithm:
Step 1: Start the program
Step 2: Get the graph as user input.
Step 3: Create a function A with parameters (Start, goal, path, level, max D).
Step 4: Ger the depth limit as user input.
Step 5: Check for the goal node and return present or not present.
Step 6: Call the function with required parameters.
Step 7: Stop the program and Exit
Program:
graph = {
'A': ['B', 'C' ],
'B': ['D', 'E'],
'C': ['F','G',],
'D': ['H', 'I'],
'E': ['J','K'],
'F':['L','M'],
'G': ['N', 'O'],
'H':[ ],
'I':[ ],
'J':[ ],
'K':[ ],
'L':[ ],
'M':[ ],
def ma(start,goal,path,level,maxd):
path.append(start)
if start==goal:
return path
if level==maxd:
return False
for child in graph [start]:
if ma(child,goal,path,level+1,maxd):
return path
path.pop()
start='A'
goal='K'
maxd=3
print()
path=list()
res=ma(start,goal,path,0,maxd)
if res:
print("path Found")
print("path=",end="")
for i in path:
print(i,end="")
if i!=path[len(path)-1]:
print(end='->')
Output:-
Result:
Thus, the python program for implementation of memory-bounded A* is executed
and its output is verified.
Algorithm:
Step1 : Start
Step 2 : Calculate the prior probability for given class labels
Step 3 : Find Likelihood probability with each attribute for each class
Step 4 : Put this value in Bayes Formula and calculate posterior
probability.
Step 5 : See which class has a higher probability, given the input belongs to
the higher probability class.
Step 6 : Stop the program
Program
import pandas as pd
from sklearn import tree
from sklearn.preprocessing import LabelEncoder
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
data = pd.read_csv('/content/tennisdata.csv')
print("The first 5 values of data is :\n",data.head())
X = data.iloc[:,:-1]
print("\nThe First 5 values of train data is\n",X.head())
y = data.iloc[:,-1]
print("\nThe first 5 values of Train output is\n",y.head())
le_Temperature = LabelEncoder()
X.Temperature = le_Temperature.fit_transform(X.Temperature)
le_Humidity = LabelEncoder()
X.Humidity = le_Humidity.fit_transform(X.Humidity)
le_Windy = LabelEncoder()
X.Windy = le_Windy.fit_transform(X.Windy)
le_PlayTennis = LabelEncoder()
y = le_PlayTennis.fit_transform(y)
print("\nNow the Train output is\n",y)
Commands:-
pip install pandas
pip install scikit-learn
Result:
Thus, the python program for implementation of naive bayes models is executed
and its output is verified.
Program:
import numpy as np
import csv
import pandas as pd
from pgmpy.models import BayesianNetwork
from pgmpy.estimators import MaximumLikelihoodEstimator
from pgmpy.inference import VariableElimination
heartDisease = pd.read_csv('heart.csv')
heartDisease = heartDisease.replace('?', np.nan)
Commands:-
pip install numpy
pip install pandas
pip install pgmpy
Output:-
Result:
Thus, the python program for implementation of bayesian network is executed and its output
is verified.
Algorithm:
Step 1 : Start
Step 2 : Import the required modules
Step 3 : Provide data to work with and eventually do appropriate transformations
Step 4 : Create a regression model and fit it with existing data
Step 5 : Check the result of model fitting to know whether the model is satisfactor
Step 6 : Apply the model for prediction
Step 7 : Print the result
Step 8 : Stop the Program
Program:
from math import ceil
import numpy as np
from scipy import linalg
import matplotlib.pyplot as plt
Output:-
Result:
Thus, the python program for implementation of regression model is executed and its output is
verified.
Algorithm:
Step 1 : Start
Step 2 : Import the necessary libraries
Step 3 : Load the Titanic dataset
Step 4 : Remove columns that are not necessary for the classification task
Step 5 : Separate inputs (features) and target (labels)
Step 6 : Convert the 'Sex' column from string to integer (male: 1, female: 2)
Step 7 : Fill missing values in the 'Age' column with the mean age
Step 8 : Split the data into training and testing sets
Step 9 : Create a decision tree classifier and train it on the training set
Step 10 : Evaluate the model on the testing set
Step 11 : Stop the program.
Program:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
# remove columns that are not necessary for the classification task
df.drop(['PassengerId', 'Name', 'SibSp', 'Parch', 'Ticket', 'Cabin', 'Embarked'], axis=1, inplace=True)
Commands:-
pip install pandas
pip install scikit-learn
Output:-
Result:
Thus, the python program for implementation of decision trees is executed and its output is
verified.
Aim:
To write a python program to implement the random forests.
Algorithm:
Step 1 : Start
Step 2 : Import the necessary libraries: sklearn.datasets, sklearn.model_selection,
sklearn.ensemble, and pandas.
Step 3 : Load the iris dataset using the load_iris() function from the sklearn.datasets
module.
Step 4 : Create a pandas DataFrame from the iris data and feature names using the
pd.DataFrame() function.
Step 5 : Add a new column 'target' to the DataFrame containing the target labels.
Step 6 : Split the data into training and testing sets using the train_test_split() function
from the sklearn.model_selection module.
Step 7 : Create a RandomForestClassifier object with default hyperparameters using the
RandomForestClassifier() function from the sklearn.ensemble module.
Step 8 : Fit the model on the training data using the fit() method of the
RandomForestClassifier object.
Step 9 : Calculate the accuracy score of the model on the testing data using the score()
method of the RandomForestClassifier object.
Step 10 : Print the accuracy score.
Step 11 : Create another RandomForestClassifier object with 40 estimators by passing
n_estimators=40 as an argument to the RandomForestClassifier() function.
Step 12 : Fit the new model on the training data using the fit() method of the
RandomForestClassifier object.
Step 13 : Stop the program.
Program:
# import necessary libraries
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
# create a pandas DataFrame from the iris data and feature names
df = pd.DataFrame(iris.data, columns=iris.feature_names)
Output:-
Result:
Thus, the python program for implementation of random forests is executed and its output is
verified.
Aim:
To write a python program to implement the svm models.
Algorithm:
Step 1 : Start
Step 2 : Import the necessary libraries.
Step 3 : Create a Pandas dataframe from the digits data and target.
Step 4 : Split the data into training and testing sets
Step 5 : Create an SVM model with radial basis function (RBF) kernel
Step 6 : Fit the RBF SVM model to the training data
Step 7 : Evaluate and print the accuracy of the RBF SVM model on the test data .
Step 8 : Create an SVM model with linear kernel
Step 9 : Fit the linear SVM model to the training data
Step 10 : Evaluate and print the accuracy of the linear SVM model on the test data
Step 11 : Stop the program.
Program:
import pandas as pd
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
# create an SVM model with radial basis function (RBF) kernel and fit it to the training data
# evaluate the accuracy of the RBF SVM model on the test data
rbf_model_score = rbf_model.score(X_test, y_test)
print("Accuracy of RBF SVM model:", rbf_model_score)
# create an SVM model with linear kernel and fit it to the training data
linear_model = SVC(kernel='linear')
linear_model.fit(X_train, y_train)
# evaluate the accuracy of the linear SVM model on the test data
linear_model_score = linear_model.score(X_test, y_test)
print("Accuracy of linear SVM model:", linear_model_score)
Command:-
pip install scikit-learn
Output:-
Result:
Thus, the python program for implementation of svm models is executed and its output is
verified.
Aim:
To write a python program to implement the ensembling techniques.
Algorithm:
Step 1 : Start
Step 2 : Import the necessary libraries.
Step 3 : Read the diabetes dataset using pd.read_csv() method and assign it to a variable
df.
Step 4 : Check the first few rows of the dataframe using df.head() method.
Step 5 : Check for missing values using df.isnull().sum() method.
Step 6 : Get summary statistics of the dataframe using df.describe() method.
Step 7 : Count the number of instances of each class in the Outcome column using
df.Outcome.value_counts() method.
Step 8 : Separate the feature variables (X) from the target variable (y) using
df.drop("Outcome", axis="columns") and df.Outcome respectively.
Step 9 : Standardize the feature variables using StandardScaler() method and assign it to a
variable scaler.
Step 10 : Split the dataset into training and testing sets with stratification using
train_test_split() method.
Step 11 : Check the dimensions of the training set
Step 12 : Calculate the proportion of class instances in the testing set
Step 13 : Calculate and print the decision and random forest classifiers
Step 14 : Stop the program.
Program:
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
# separate the feature variables (X) from the target variable (y)
X = df.drop("Outcome", axis="columns")
y = df.Outcome
# split the dataset into training and testing sets with stratification
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, stratify=y, random_state=10)
Command:-
pip install scikit-learn
Output:-
Result:
Thus, the python program for implementation of ensembling techniques is executed and its
output is verified.
Aim:
To write a python program to implement the clustering algorithm.
Algorithm:
Step 1 : Start
Step 2 : Import the necessary libraries.
Step 3 : Load the dataset using pandas read_csv method.
Step 4 : Plot the dataset using matplotlib scatter plot to visualize the relationship between
'Age' and 'Income($)'.
Step 5 : Create a KMeans model with the desired number of clusters (n_clusters) and
number of times the algorithm will be run with different centroid seeds (n_init).
Step 6 : Predict the cluster for each data point in the dataset using the KMeans model's
fit_predict method.
Step 7 : Assign the predicted clusters to the dataset by adding a new column called
'cluster'.
Step 8 : Plot the dataset again, but this time color-coded based on their predicted clusters,
and mark the centroid of each cluster using a different marker and color.
Step 9 : To improve the accuracy of the clustering model, scale the 'Age' and 'Income($)'
features using MinMaxScaler. Then, repeat steps 4 to 7.
Step 10 : Plot the elbow curve to determine the optimal number of clusters by computing
the sum of squared distances between data points and their assigned cluster
centers for different values of k.
Step 11 : Stop the program.
Program:
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import MinMaxScaler
# Load data
df = pd.read_csv("/content/income (1).csv")
# Plot clusters
colors = ['green', 'red', 'black']
centroids = kmeans.cluster_centers_
for i in range(3):
plt.scatter(df[df['cluster'] == i]['Age'], df[df['cluster'] == i]['Income($)'], color=colors[i])
plt.scatter(centroids[:, 0], centroids[:, 1], color='purple', marker='*', label='centroid')
plt.xlabel('Age')
plt.ylabel('Income ($)')
plt.legend()
plt.show()
Output:-
Aim:
To write a python program to implement the em for Bayesian networks.
Algorithm:
Step 1 : Start
Step 2 : Define the Bayesian network structure (DAG) and the conditional probability
tables (CPTs) for each variable.
Step 5 : Define the E-step function that takes the observed data and current parameters
as inputs and returns the posterior probabilities for each data point.
Step 6 : Define the M-step function that takes the observed data and posterior
probabilities as inputs and updates the parameters using the observed data and
posterior probabilities.
Step 8 : In each iteration, call the E-step function to compute the posterior probabilities,
followed by the M-step function to update the parameters.
Step 9 : After the specified number of iterations, the final CPTs will be the estimated
probabilities for each variable given the observed data.
Program:
import numpy as np
dag = [[], [0]]
for i in range(10):
posterior = e_step(data, params)
params = m_step(data, posterior)
print(params['cpt0'])
print(params['cpt1'])
Result:
Thus, the python program for implementation of em for Bayesian networks is executed and its
output is verified
Aim:
To write a python program to implement the simple nn models.
Algorithm:
Step 1 : Start
Step 5 : Compile the model by specifying the loss function, optimizer, and evaluation
metrics
Program:
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
Commands:-
pip install numpy
pip install keras
pip install tensorflow or pip install tensorflow-gpu
Output:-
Result:
Thus, the python program for implementation of simple nn models is executed and its output
is verified.
Aim:
To write a python program to implement the deep learning nn models.
Algorithm:
Step 1 : Start
Step 5 : Compile the model by specifying the loss function, optimizer, and evaluation
metrics
Program:
import tensorflow as tf
import numpy as np
model = tf.keras.Sequential([
tf.keras.layers.Dense(4, activation='relu', input_shape=(2,)),
tf.keras.layers.Dense(4, activation='relu'),
tf.keras.layers.Dense(4, activation='relu'),
tf.keras.layers.Dense(4, activation='relu'),
tf.keras.layers.Dense(4, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
Commands:-
pip install numpy
pip install keras
pip install tensorflow or pip install tensorflow-gpu
Output:-
Result:
Thus, the python program for implementation of deep learning nn models is executed and its
output is verified.