0% found this document useful (0 votes)
18 views42 pages

Aiml Record

The document outlines the implementation of various search algorithms and machine learning models in Python, including uninformed search algorithms (BFS, DFS), informed search algorithms (A*, memory-bounded A*), Naïve Bayes model, Bayesian networks, and regression models. Each section provides an aim, algorithm steps, and a program code snippet demonstrating the implementation. The results indicate successful execution and output for each implemented algorithm and model.

Uploaded by

Celin Narayanan
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)
18 views42 pages

Aiml Record

The document outlines the implementation of various search algorithms and machine learning models in Python, including uninformed search algorithms (BFS, DFS), informed search algorithms (A*, memory-bounded A*), Naïve Bayes model, Bayesian networks, and regression models. Each section provides an aim, algorithm steps, and a program code snippet demonstrating the implementation. The results indicate successful execution and output for each implemented algorithm and model.

Uploaded by

Celin Narayanan
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/ 42

Ex.No : 1 .

Implementation of Uninformed search algorithms


(BFS, DFS)
Date :

AIM:
To implement uninformed search algorithms(BFS,DFS) in python.

ALGORITHM:
Breadth-First Search (BFS) Algorithm:
STEP1. Initialize an empty queue and a visited set.
STEP2. Enqueue the starting node into the queue.
STEP3. Mark the starting node as visited.
STEP4. While the queue is not empty, do the following:
- Dequeue a node from the front of the queue.
- Process the dequeued node (e.g., print or perform any required operations).
- Enqueue all the unvisited neighboring nodes of the dequeued node into the queue.
- Mark each neighboring node as visited.
STEP5. Repeat steps 4 until the queue becomes empty.
STEP6. If there are still unvisited nodes in the graph, choose another unvisited node as
the new starting point and repeat steps 2 to 5.

Depth-First Search (DFS) Algorithm:


STEP1. Initialize a stack and a visited set.
STEP2. Push the starting node onto the stack.
STEP3. Mark the starting node as visited.
STEP4. While the stack is not empty, do the following:
- Pop a node from the top of the stack.
- Process the popped node (e.g., print or perform any required operations).
- Push all the unvisited neighboring nodes of the popped node onto the stack.
- Mark each neighboring node as visited.
STEP5. Repeat steps 4 until the stack becomes empty.
STEP6. If there are still unvisited nodes in the graph, choose another unvisited node as
the new starting point and repeat steps 2 to 5.
PROGRAM:

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

def bfs(graph, start, goal):


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

while queue:
path = queue.pop(0)
node = path[-1]

if node == goal:
return path

if node not in visited:


visited.add(node)

for adjacent in graph[node]:


new_path = list(path)
new_path.append(adjacent)
queue.append(new_path)

return "No path found"

def dfs(graph, start, goal):


stack = [[start]]
visited = set()

while stack:
path = stack.pop()
node = path[-1]

if node == goal:
return path
if node not in visited:
visited.add(node)

for adjacent in graph[node]:


new_path = list(path)
new_path.append(adjacent)
stack.append(new_path)

return "No path found"

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


print(dfs(graph, 'A', 'F'))
Output:

RESULT:

Thus the program to implement Uninformed search algorithms in python is executed


successfully and the required output is obtained.
Ex.No : 2 .Implementation of Informed search algorithms (A*,
memory-bounded A*)
Date :

AIM:
To implement informed search algorithms(A*, memory-bounded A*) in python.

ALGORITHM:

A* Algorithm:
STEP1. Initialize open and closed lists.
STEP2. Add starting node to the open list.
STEP3. While open list is not empty:
- Select node with lowest cost from open list as current node.
- Move current node to closed list.
- If current node is the goal node, exit.
- Generate neighboring nodes.
- Calculate g and h values for each neighbor.
- If neighbor is in closed list, skip it.
- If neighbor is not in open list, add it.
- If neighbor is in open list, update if new g value is lower.
STEP4. If open list is empty and goal node not reached, no path exists.

Memory Bounded A* (MA*) Algorithm:


STEP1. Initialize open and closed lists.
STEP2. Add starting node to open list.
STEP3. While open list is not empty:
- Select node with lowest cost from open list as current node.
- Move current node to closed list.
- If current node is the goal node, exit.
- Generate neighboring nodes.
- Calculate g and h values for each neighbor.
- If neighbor is in closed list, skip it.
- If neighbor is not in open list, add it.
- If neighbor is in open list, update if new g value is lower.
- If memory usage exceeds threshold, terminate.
STEP4. If open list is empty and goal node not reached, no path exists.

PROGRAM:

import heapq

grid = [[0, 0, 1, 0, 0, 0, 1, 0],


[0, 0, 1, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0]]

start = (0, 0)
goal = (5, 7)

# A* Algorithm
def astar(grid, start, goal):
open_list = [(0, start)]
closed_list = set()
g_score = {start: 0} # start node's g score is 0
h_score = {start: heuristic(start, goal)}
parent = {start: None}

while open_list:
current = heapq.heappop(open_list)[1]

if current == goal:
return reconstruct_path(parent, current)

closed_list.add(current)

for neighbor in get_neighbors(grid, current):


if neighbor in closed_list:
continue

new_g_score = g_score[current] + 1
if neighbor not in [item[1] for item in open_list]:
heapq.heappush(open_list, (new_g_score + heuristic(neighbor, goal),
neighbor))
elif new_g_score >= g_score[neighbor]:
continue

parent[neighbor] = current
g_score[neighbor] = new_g_score
h_score[neighbor] = heuristic(neighbor, goal)

return None

# Memory-Bounded A* Algorithm
# Memory-Bounded A* Algorithm
def memory_bounded_astar(grid, start, goal, memory_limit):
open_list = [(0, start)]
closed_list = set()
g_score = {start: 0} # start node's g score is 0
h_score = {start: heuristic(start, goal)} # start node's h score is estimated usin
g the heuristic function
parent = {start: None}

while open_list:
current = heapq.heappop(open_list)[1]

if current == goal:
return reconstruct_path(parent, current)

closed_list.add(current)

for neighbor in get_neighbors(grid, current):


if neighbor in closed_list:
continue

new_g_score = g_score[current] + 1

if neighbor not in [item[1] for item in open_list]:


heapq.heappush(open_list, (new_g_score + heuristic(neighbor, goal),
neighbor))
elif new_g_score >= g_score[neighbor]:
continue
parent[neighbor] = current
g_score[neighbor] = new_g_score
h_score[neighbor] = heuristic(neighbor, goal)

while len(open_list) > memory_limit:


node_to_remove = heapq.nlargest(1, open_list)[0] # get the node with th
e highest f score
open_list.remove(node_to_remove) # remove the node from the open lis
t
del g_score[node_to_remove[1]] # remove the node's g score from the di
ctionary

return None

def heuristic(node, goal):


x1, y1 = node
x2, y2 = goal
return abs(x1 - x2) + abs(y1 - y2)

def get_neighbors(grid, node):


row, col = node
neighbors = []

# Check north neighbor


if row > 0 and grid[row-1][col] == 0:
neighbors.append((row-1, col))

# Check south neighbor


if row < len(grid) - 1 and grid[row+1][col] == 0:
neighbors.append((row+1, col))

# Check west neighbor


if col > 0 and grid[row][col-1] == 0:
neighbors.append((row, col-1))

# Check east neighbor


if col < len(grid[0]) - 1 and grid[row][col+1] == 0:
neighbors.append((row, col+1))

return neighbors

def reconstruct_path(parent, current):


path = [current]
while current in parent:
current = parent[current]
path.append(current)
path.reverse()
return path

memory_limit = 1000000000 # 1 GB

result = astar(grid, start, goal)


print(result)
wwssssssssss
result = memory_bounded_astar(grid, start, goal, memory_limit)
print(result)
OUTPUT:

RESULT:

Thus the program to implement Informed search algorithms in python is executed


successfully and the required output is obtained.
Ex.No : 3 Implement Naive Bayes model

Date :

AIM:
To implement Naïve Bayes Model in python.

ALGORITHM

STEP1. Import the necessary libraries:


- Import `sklearn` to access the machine learning algorithms.
STEP2. Load and preprocess the dataset:
- Load the dataset and split it into features (X) and the target variable (y).
STEP3. Split the data into training and testing sets:
- Split the dataset into training and testing sets using the `train_test_split` function
from `sklearn.model_selection`.
- Assign the training features and labels to `X_train` and `y_train`.
- Assign the testing features and labels to `X_test` and `y_test`.
STEP4. Create and train the Naive Bayes model:
- Create an instance of the chosen Naive Bayes class (Gaussian).
- Train the model using the training data by calling the `fit` method with `X_train` and
`y_train` as arguments.
STEP5. Use the trained model to make predictions on the testing data by calling the
`predict` method with `X_test` as an argument.
- Evaluate the performance of the model using appropriate evaluation metrics from
`sklearn.metrics`, such as accuracy.
STEP6.Use the trained model for prediction:
- Once the model is trained and evaluated, you can use it to make predictions on new,
unseen data by calling the `predict` method with the new data as an argument.
PROGRAM:

from sklearn.datasets import load_iris


from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
iris = load_iris()
X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
random_state=42)
model = GaussianNB()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
OUTPUT:

RESULT:

Thus the program to implement Naïve Bayes Model in python is executed successfully
and the required output is obtained.
Ex.No : 4 Implement Bayesian Networks

Date :

AIM:
To implement Bayesian Networks in python.

ALGORITHM:

STEP1.Import the necessary libraries:


- Import the required libraries, such as `pandas` for data manipulation, `pgmpy` for
probabilistic graphical models, and `numpy` for numerical operations.
STEP2.Define the structure of the Bayesian network:
- Create an instance of `BayesianModel` from `pgmpy.models` to represent the
Bayesian network.
- Define the nodes (variables) of the network using `add_nodes_from` method and
specify their names.
STEP3. Define the conditional probability distributions :
- Use the `add_edges_from` method to specify the edges (dependencies) between the
nodes.
- Create the CPDs for each node using `TabularCPD` from `pgmpy.factors.discrete`
and specify the probabilities based on your domain knowledge or data.
STEP4.Fit the Bayesian network to data:
- If you have data available, you can use the `fit` method of the BayesianModel object
to learn the CPDs from data.
STEP5.Perform inference with the Bayesian network:
- Use the `VariableElimination` class from `pgmpy.inference` to perform inference on
the Bayesian network.
- Provide the evidence (observed variables) and query the target variables using the
`query` method.
STEP6.Visualize the Bayesian network:
- Optionally, you can use the `draw` method from `pgmpy.models.BayesianModel` to
visualize the Bayesian network.
STEP7. Use the Bayesian network for prediction:
- Once the model is trained and the inference is performed, you can use the Bayesian
network to make predictions by providing evidence and querying the target variables.
PROGRAM:

from ctypes import c_double


# Import required libraries
from pgmpy.models import BayesianModel
from pgmpy.factors.discrete import TabularCPD
from pgmpy.inference import VariableElimination
import numpy as np

# Define the Bayesian Network


model = BayesianModel([('A', 'C'), ('B', 'C'), ('C', 'D'), ('C', 'E')])

# Define the Conditional Probability Distributions (CPDs)


a=[[0.4, 0.6]]
a_=np.reshape(a,(2,1))
b=[[0.7, 0.3]]
b_=np.reshape(b,(2,1))
c_=np.reshape([[0.1, 0.2, 0.7, 0.3],[0.8, 0.7, 0.2, 0.6],[0.1, 0.1, 0.1, 0.1]],(3,4))
cpd_a = TabularCPD(variable='A', variable_card=2, values=a_)
cpd_b = TabularCPD(variable='B', variable_card=2, values=b_)
cpd_c = TabularCPD(variable='C', variable_card=3,
values=c_,
evidence=['A', 'B'], evidence_card=[2, 2])
cpd_d = TabularCPD(variable='D', variable_card=2,
values=[[0.9, 0.3, 0.4], [0.1, 0.7, 0.6]],
evidence=['C'], evidence_card=[3])
cpd_e = TabularCPD(variable='E', variable_card=2,
values=[[0.3, 0.6, 0.8], [0.7, 0.4, 0.2]],
evidence=['C'], evidence_card=[3])

# Add the CPDs to the model


model.add_cpds(cpd_a, cpd_b, cpd_c, cpd_d, cpd_e)

# Check if the model is valid


model.check_model()

# Perform variable elimination inference


inference = VariableElimination(model)

# Compute the probability distribution of D given evidence of A=0 and


E=1query=inference.query(variables=['D'], evidence={'A': 0, 'E': 1}) print(query)
Output:

RESULT:

Thus the program to implement Bayesian Network in python is executed successfully


and the required output is obtained.
Ex.No : 5 Build Regression models

Date :

AIM:
To build Regression models in python.

ALGORITHM:

STEP1.Import the necessary libraries: pandas, numpy, sklearn.


STEP2.Load and preprocess the dataset: Split the data into features (X) and target
variable (y), and perform any necessary preprocessing.
STEP3.Split the data into training and testing sets using train_test_split.
STEP4.Create and train the regression model: Choose a regression algorithm (e.g.,
Linear Regression, Decision Tree Regression, Random Forest Regression), create an
instance of the chosen class, and train the model using the training data.
STEP5.Make predictions and evaluate the model: Use the model to predict the target
variable for the testing data, and evaluate its performance using appropriate metrics.
STEP6.Use the trained model for prediction: Apply the trained model to make
predictions on new data.

PROGRAM:

from sklearn.datasets import fetch_california_housing


from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error

# Load the California Housing dataset


housing = fetch_california_housing()

# Split the data into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(housing.data, housing.target, te
st_size=0.2, random_state=42)

# Train a linear regression model


lr = LinearRegression()
lr.fit(X_train, y_train)
# Make predictions on the testing set
y_pred_lr = lr.predict(X_test)

# Calculate the mean squared error for the linear regression model
mse_lr = mean_squared_error(y_test, y_pred_lr)
print(f"Linear Regression Mean Squared Error: {mse_lr:.2f}")

# Train a random forest regression model


rf = RandomForestRegressor(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)

# Make predictions on the testing set


y_pred_rf = rf.predict(X_test)

# Calculate the mean squared error for the random forest regression model
mse_rf = mean_squared_error(y_test, y_pred_rf)
print(f"Random Forest Mean Squared Error: {mse_rf:.2f}")
OUTPUT:

RESULT:

Thus the program to build regression model in python is executed successfully and the
required output is obtained.
Ex.No : 6 Build decision trees and random forests

Date :

AIM:
To build decision trees and random forests in python.

ALGORITHM:

STEP1. Import libraries: pandas, sklearn.


STEP2.Load and preprocess the dataset.
STEP3.Split the data into training and testing sets.
STEP4.Create and train a decision tree model using the training data.
STEP5.Evaluate the decision tree model using the testing data.
STEP6. Create and train a random forest model using the training data.
STEP7. Evaluate the random forest model using the testing data.

PROGRAM:

from sklearn.datasets import load_iris


from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score

# Load the iris dataset


iris = load_iris()
X = iris.data
y = iris.target

# Split the data into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_st
ate=42)

# Initialize the decision tree model


dt_model = DecisionTreeClassifier(max_depth=3, random_state=42)

# Train the decision tree model on the training data


dt_model.fit(X_train, y_train)
# Evaluate the performance of the decision tree model on the testing data
dt_pred = dt_model.predict(X_test)
dt_acc = accuracy_score(y_test, dt_pred)

# Initialize the random forest model


rf_model = RandomForestClassifier(n_estimators=100, max_depth=3, random_
state=42)

# Train the random forest model on the training data


rf_model.fit(X_train, y_train)

# Evaluate the performance of the random forest model on the testing data
rf_pred = rf_model.predict(X_test)
rf_acc = accuracy_score(y_test, rf_pred)

# Output the accuracy scores of the models


print(f"Decision Tree Accuracy: {dt_acc}")
print(f"Random Forest Accuracy: {rf_acc}")
OUTPUT

RESULT:

Thus the program to build decision tree and random forest in python is executed
successfully and the required output is obtained.
Ex.No : 7 Build SVM model
Date :

AIM:
To build a SVM model in python.

ALGORITHM:

STEP1. Import the necessary libraries: pandas, sklearn.


STEP2. Load and preprocess the dataset.
STEP3. Split the data into training and testing sets.
STEP4. Create and train the SVM model:
- Import the `SVC` class from `sklearn.svm`.
- Create an instance of the `SVC` class with any desired parameters.
- Train the model using the training data.
STEP5. Make predictions and evaluate the model:
- Use the trained model to make predictions on the testing data.
- Evaluate the performance of the model using appropriate evaluation metrics.

PROGRAM:

# import required libraries


from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
# load dataset
iris = datasets.load_iris()

# split dataset into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target,
test_size=0.3, random_state=0)

# initialize SVM classifier with linear kernel


svm = SVC(kernel='linear')

# train SVM classifier on training set


svm.fit(X_train, y_train)
# make predictions on testing set
y_pred = svm.predict(X_test)
# calculate accuracy of predictions
accuracy = accuracy_score(y_test, y_pred)
# print accuracy of predictions
print('Accuracy:', accuracy)
Output :

RESULT:

Thus the program to build SVM model in python is executed successfully and the
required output is obtained.
Ex.No : 8 Implement ensembling technique
Date :

AIM:
To implement Ensembling Technique in python.

ALGORITHM:

STEP1.Import the necessary libraries: pandas, sklearn.


STEP2.Load and preprocess the dataset.
STEP3. Split the data into training and testing sets.
STEP4. Create and train the ensemble model:
- Import the ensemble class from sklearn.ensemble (e.g., RandomForestClassifier for
classification or RandomForestRegressor for regression).
- Create an instance of the ensemble class with any desired parameters.
- Train the ensemble model using the training data.
STEP5. Make predictions and evaluate the model:
- Use the trained ensemble model to make predictions on the testing data.
- Evaluate the performance of the model using appropriate evaluation metrics.

PROGRAM:

from sklearn.datasets import load_iris


from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# load dataset
iris = load_iris()

# split dataset into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target,
test_size=0.3, random_state=0)

# initialize random forest classifier with 10 trees


rfc = RandomForestClassifier(n_estimators=10)
# train the random forest classifier on the training set
rfc.fit(X_train, y_train)
# make predictions on the testing set
y_pred = rfc.predict(X_test)

# calculate accuracy of predictions


accuracy = accuracy_score(y_test, y_pred)

# print accuracy of predictions


print('Accuracy:', accuracy)
Output:

RESULT:

Thus the program to implement Ensembling Teechnique in python is executed


successfully and the required output is obtained.
Ex.No : 9 Implement clustering algorithms
Date :

AIM:
To implement Clustering Algorithms in python.

ALGORITHM:

STEP1.Import the necessary libraries: pandas, sklearn.


STEP2.Load and preprocess the dataset.
STEP3.Choose the number of clusters:
- Decide on the desired number of clusters based on your problem and domain
knowledge.
STEP4.Create and train the clustering model:
- Import the clustering algorithm from sklearn.cluster (e.g., KMeans for K-means
clustering, AgglomerativeClustering for hierarchical clustering).
- Create an instance of the chosen clustering algorithm with any desired parameters.
- Train the clustering model using the data.
STEP5.Assign cluster labels and analyze results:
- Obtain the cluster labels assigned by the clustering model to each data point.
- Analyze the results by examining the clusters and their characteristics.

PROGRAM:

from sklearn.cluster import KMeans


from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
# generate sample data
X, y_true = make_blobs(n_samples=300, centers=4, cluster_std=0.60,
random_state=0)
# initialize k-means clustering algorithm with 4 clusters
kmeans = KMeans(n_clusters=4)

# train the k-means clustering algorithm on the sample data


kmeans.fit(X)
# get the predicted cluster labels for the sample data
y_pred = kmeans.predict(X)

# plot the sample data with predicted cluster labels


plt.scatter(X[:, 0], X[:, 1], c=y_pred, s=50, cmap='viridis')
plt.show()
OUTPUT:

RESULT:

Thus the program to implement Clustering Algorithm in python is executed successfully


and the required output is obtained.
Ex.No : 10 Implement EM for Bayesian networks
Date :

AIM:
To implement EM for Bayesian Networks in python.

ALGORITHM:

STEP1.Import the necessary libraries: pandas, numpy.


STEP2.Define the Bayesian network structure.
STEP3.Initialize the parameters.
STEP4.Expectation step: Calculate expected sufficient statistics using observed data and
current parameter estimates.
STEP5.Maximization step: Update parameters based on the expected sufficient
statistics.
STEP6.Repeat steps 4 and 5 until convergence or a specified number of iterations.
STEP7. Predict or infer using the trained Bayesian network.

PROGRAM:

import numpy as np
from collections import defaultdict

class BayesianNetwork:
def init (self, structure):
self.structure = structure
self.nodes = sorted(list(self.structure.keys()))
self.parents = defaultdict(list)
for child, parents in self.structure.items():
for parent in parents:
self.parents[child].append(parent)

class EM:
def init (self, bn, data):
self.bn = bn
self.data = data
def run(self, num_iterations=100, tolerance=1e-4):
# Initialize parameters
pi = defaultdict(float)
theta = defaultdict(lambda: defaultdict(float))
for i in range(len(self.bn.nodes)):
node = self.bn.nodes[i]
pi[node] = np.mean(self.data[:, i])
for parent in self.bn.parents[node]:
parent_index = self.bn.nodes.index(parent)
parent_data = self.data[:, parent_index]
for parent_value in np.unique(parent_data):
parent_mask = parent_data == parent_value
theta[parent][parent_value, node] = np.mean(self.data[parent_mask, i])

# Run EM algorithm
for iteration in range(num_iterations):
# E-step: Compute expected sufficient statistics
pi_new = defaultdict(float)
theta_new = defaultdict(lambda: defaultdict(float))
for i in range(len(self.bn.nodes)):
node = self.bn.nodes[i]
pi_new[node] = np.mean(self.data[:, i])
for parent in self.bn.parents[node]:
parent_index = self.bn.nodes.index(parent)
parent_data = self.data[:, parent_index]
for parent_value in np.unique(parent_data):
parent_mask = parent_data == parent_value
theta_new[parent][parent_value, node] = np.mean(self.data[pare
nt_mask, i])

# M-step: Update parameters


pi_change = np.abs(np.array(list(pi.values())) - np.array(list(pi_new.valu
es()))).max()
theta_change = 0
for node in theta:
node_theta_change = np.abs(np.array(list(theta[node].values())) - np.a
rray(list(theta_new[node].values()))).max()
theta_change = max(theta_change, node_theta_change)
if pi_change < tolerance and theta_change < tolerance:
break

pi = pi_new
theta = theta_new
return pi, theta

# Example usage
structure = {0: [], 1: [0], 2: [0], 3: [1, 2]}
data = np.array([[0, 0, 0, 0], [0, 0, 0, 1], [1, 1, 0, 0], [1, 1, 1, 1]])
bn = BayesianNetwork(structure)
em = EM(bn, data)
pi, theta = em.run()
print("pi:", pi)
print("theta:", theta)
Output:

RESULT:

Thus the program to implement EM for Bayesian networks in python is executed


successfully and the required output is obtained.
Ex.No : 11 Build Simple NN Models
Date :

AIM:
To build simple NN models in python.

ALGORITHM:

STEP1.Load the MNIST dataset using Keras.


STEP2.Preprocess the data .
STEP3.Split the data into training and testing sets.
STEP4.Define the neural network architecture.
STEP5.Compile the model.
STEP6.Train the model.
STEP7.Evaluate the model.

PROGRAM:

# Load the MNIST dataset using Keras


from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()

# Preprocess the data


x_train = x_train / 255.0
x_test = x_test / 255.0

# Split the data into training and testing sets


from sklearn.model_selection import train_test_split
x_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size=0.2)

# Define the neural network architecture


from keras.models import Sequential
from keras.layers import Dense, Flatten

model = Sequential()
model.add(Flatten(input_shape=(28, 28)))
model.add(Dense(128, activation='relu'))
model.add(Dense(10, activation='softmax'))

# Compile the model


model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metri
cs=['accuracy'])

# Train the model


model.fit(x_train, y_train, batch_size=32, epochs=10, validation_data=(x_val, y
_val))

# Evaluate the model


loss, accuracy = model.evaluate(x_test, y_test)
print("Test accuracy:", accuracy)
OUTPUT:

RESULT:

Thus the program to build simple NN Models in python is executed successfully and the
required output is obtained.
Ex.No : 12 Build deep learning NN models
Date :

AIM:
To build deep learning NN models in python.

ALGORITHM:

STEP1.Import the necessary libraries: TensorFlow/Keras, numpy.


STEP2.Load and preprocess the dataset.
STEP3.Define the neural network architecture.
STEP4.Create and compile the model.
STEP5.Train the model using the training data.
STEP6.Evaluate the model's performance using the test data.
STEP7.Make predictions using the trained model.

PROGRAM:

# Import necessary libraries


import tensorflow as tf
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, D
ropout

# Load the CIFAR-10 dataset


(x_train, y_train), (x_test, y_test) = cifar10.load_data()

# Normalize the data


x_train = x_train / 255.0
x_test = x_test / 255.0

# Define the model architecture


model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
MaxPooling2D((2, 2)),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Conv2D(128, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Flatten(),
Dense(128, activation='relu'),
Dropout(0.5),
Dense(10, activation='softmax')
])

# Compile the model


model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metri
cs=['accuracy'])

# Train the model


model.fit(x_train, y_train, epochs=10, validation_data=(x_test, y_test))

# Evaluate the model

test_loss, test_acc = model.evaluate(x_test, y_test)

print(f'Test accuracy: {test_acc}')


OUTPUT:

RESULT:

Thus the program to build deep learning NN Models in python is executed successfully
and the required output is obtained.

You might also like