0% found this document useful (0 votes)
58 views28 pages

Department of Computer Science & Engineering Practical File Subject: Artificial Intelligence Lab (BTCS 605-18) B. Tech - 6 Semester (Batch 2020-24)

The document provides instructions for 12 experiments related to artificial intelligence and machine learning algorithms. The experiments cover topics like uninformed search, informed search, game search, Bayesian networks, reinforcement learning, and more. Code snippets in C++ are provided for implementations of algorithms like breadth first search, depth first search, A* search, and best first search. The document includes objectives, explanations of concepts, pseudocode, and expected output for each experiment.

Uploaded by

Pankaj Kumar
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)
58 views28 pages

Department of Computer Science & Engineering Practical File Subject: Artificial Intelligence Lab (BTCS 605-18) B. Tech - 6 Semester (Batch 2020-24)

The document provides instructions for 12 experiments related to artificial intelligence and machine learning algorithms. The experiments cover topics like uninformed search, informed search, game search, Bayesian networks, reinforcement learning, and more. Code snippets in C++ are provided for implementations of algorithms like breadth first search, depth first search, A* search, and best first search. The document includes objectives, explanations of concepts, pseudocode, and expected output for each experiment.

Uploaded by

Pankaj Kumar
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/ 28

Department of Computer Science & Engineering

Practical File
Subject: Artificial Intelligence Lab
(BTCS 605-18)
B. Tech – 6th Semester
[Batch 2020-24]

Chandigarh Group of Colleges


College of Engineering, Landran, Mohali-140307

Submitted To: Submitted By:


Dr. Seema Pawan Kumar
2018982
INDEX
S. No Name of Experiment Date Remarks

Write a program to conduct uninformed search and


1
informed search.

2 Write a program to conduct uninformed search


(Breadth First Search)
3 Write a program to conduct uninformed search
(Depth First Search)
4 Implementation of informed search (Best First
Search)
Implementation of informed search Strategy (A*
5 Search).

6 Write a program to conduct game search.

Implementation of Game Search using MINIMAX


7
Algorithm.

Write a program to construct a Bayesian network


8
from given data.

9 Write a program to infer from the Bayesian network.

Write a program to run value and policy iteration in


10
a grid world.

11 Write a program to do reinforcement learning in a


grid world.
Experiment – 1
Aim:- Write a program to conduct uninformed search and informed search.

Informed Search

• They contain information on goal state.


• It helps search efficiently.
• The information is obtained by a function that helps estimate how close a current state
is, to the goal state.
• Examples of informed search include greedy search and graph search.

Uninformed Search

• They don’t have any additional information.


• The information is only provided in the problem definition.
• The goal state can be reached using different order and length of actions.
• Examples of uninformed search include depth first search (DFS) and breadth first
search (BFS).

The difference between informed search and uninformed search −

Parameters Informed Search Uninformed Search


Known as It is also known as Heuristic Search. It is also known as Blind Search.
It uses knowledge for the searching It doesn’t use knowledge for the
Using Knowledge
process. searching process.
It finds solution slow as
Performance It finds a solution more quickly.
compared to an informed search.
Completion It may or may not be complete. It is always complete.
Cost Factor Cost is low. Cost is high.
It consumes less time because of quick It consumes moderate time
Time
searching. because of slow searching.
There is a direction given about the No suggestion is given regarding
Direction
solution. the solution in it.
It is lengthier while
Implementation It is less lengthy while implemented.
implemented.
It is more efficient as efficiency takes It is comparatively less efficient
into account cost and performance. as incurred cost is more and the
Efficiency
The incurred cost is less and speed of speed of finding the Breadth-
finding solutions is quick. First solution is slow.
Computational Computational requirements are Comparatively higher
requirements lessened. computational requirements.
Size of search Having a wide scope in terms of Solving a massive search task is
problems handling large search problems. challenging.
Examples of • Greedy Search
• Depth First Search (DFS)
Algorithms • A* Search
Parameters Informed Search Uninformed Search
• AO* Search • Breadth First Search
• Hill Climbing Algorithm (BFS)
• Branch and bound
Experiment – 2
Aim: - Write a programme to conduct uninformed search (Breadth First Search).
Breadth First Search

#include <bits/stdc++.h>
using namespace std;
class Graph {
int V;
vector<list<int> > adj;
public:
Graph(int V);
void addEdge(int v, int w);
void BFS(int s);
};
Graph::Graph(int V)
{
this->V = V;
adj.resize(V);
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}
void Graph::BFS(int s)
{
vector<bool> visited;
visited.resize(V, false);
list<int> queue;
visited[s] = true;
queue.push_back(s);
while (!queue.empty()) {
s = queue.front();
cout << s << " ";
queue.pop_front();
for (auto adjecent : adj[s]) {
if (!visited[adjecent]) {
visited[adjecent] = true;
queue.push_back(adjecent);
}
}
}
}
int main()
{
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
cout << "Following is Breadth First Traversal "
<< "(starting from vertex 2) \n";
g.BFS(2);
return 0;
}

Output: -
Experiment – 3
Aim: - Write a program to conduct uninformed search (Depth First Search).

Depth First Search

#include <iostream>
#include <list>
using namespace std;
class DFSGraph
{
int V;
list<int> *adjList;
void DFS_util(int v, bool visited[]);
public:
DFSGraph(int V)
{
this->V = V;
adjList = new list<int>[V];
}
void addEdge(int v, int w){
adjList[v].push_back(w);
}
void DFS();
};
void DFSGraph::DFS_util(int v, bool visited[])
{
visited[v] = true;
cout << v << " ";
list<int>::iterator i;
for(i = adjList[v].begin(); i != adjList[v].end(); ++i)
if(!visited[*i])
DFS_util(*i, visited);
}
void DFSGraph::DFS()
{
bool *visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;
for (int i = 0; i < V; i++)
if (visited[i] == false)
DFS_util(i, visited);
}
int main()
{
DFSGraph gdfs(5);
gdfs.addEdge(0, 1);
gdfs.addEdge(0, 2);
gdfs.addEdge(0, 3);
gdfs.addEdge(1, 2);
gdfs.addEdge(2, 4);
gdfs.addEdge(3, 3);
gdfs.addEdge(4, 4);
cout << "Depth-first traversal for the given graph:"<<endl;
gdfs.DFS();
return 0;
}

Output: -
Experiment – 4

Aim: - Implementation of informed search (Best First Search)


Best First Search

#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pi;
vector<vector<pi> > graph;
void addedge(int x, int y, int cost)
{
graph[x].push_back(make_pair(cost, y));
graph[y].push_back(make_pair(cost, x));
}
void best_first_search(int actual_Src, int target, int n)
{
vector<bool> visited(n, false);
priority_queue<pi, vector<pi>, greater<pi> > pq;
pq.push(make_pair(0, actual_Src));
int s = actual_Src;
visited[s] = true;
while (!pq.empty()) {
int x = pq.top().second;
cout << x << " ";
pq.pop();
if (x == target)
break;
for (int i = 0; i < graph[x].size(); i++) {
if (!visited[graph[x][i].second]) {
visited[graph[x][i].second] = true;
pq.push(make_pair(graph[x][i].first,graph[x][i].second));
}
}
}
}
int main()
{
int v = 14;
graph.resize(v);
addedge(0, 1, 3);
addedge(0, 2, 6);
addedge(0, 3, 5);
addedge(1, 4, 9);
addedge(1, 5, 8);
addedge(2, 6, 12);
addedge(2, 7, 14);
addedge(3, 8, 7);
addedge(8, 9, 5);
addedge(8, 10, 6);
addedge(9, 11, 1);
addedge(9, 12, 10);
addedge(9, 13, 2);
int source = 0;
int target = 9;
cout << "Best First Search:"<<endl;
best_first_search(source, target, v);
return 0;
}

Output: -
Experiment – 5

Aim: - Implementation of informed search Strategy (A*Search)


#include <iostream>
#include <cmath>
#include <list>
#include <vector>
#include <algorithm>

class Vector2
{
int x, y;
public:
Vector2(int _x, int _y) : x(_x), y(_y) {}
Vector2() = default;
Vector2 operator +(const Vector2& other)
{
Vector2 temp;
temp.x = this->x + other.x;
temp.y = this->y + other.y;
return temp;
}
int getX() const { return x; }
int getY() const { return y; }

friend class Map;


};

struct Node
{
Vector2 position;
int G, H, F;
Node* parent = nullptr;

Node() = default;
Node(const Node& other) = default;
Node(Vector2 pos):position(pos) {};

void calc(const Vector2& endPos) {


H = static_cast<int>((abs(static_cast<double>(position.getX() - endPos.getX())) +
abs(static_cast<double>(position.getY() - endPos.getY()))));
G = parent ? parent->G + 1 : 1;
F = G + H;
}

bool operator==(const Node& other) const {


return (position.getX() == other.position.getX() && position.getY() ==
other.position.getY());
}
bool operator!=(const Node& other) const {
return !(*this == other);
}
bool operator<(const Node& other) const {
return(F < other.F);
}
};

class Map
{
std::vector<char> data;
int size;
public:
Map() = default;
Map(int _size) : size(_size) {
data.resize(size * size);
for (int i = 0; i < size * size; ++i) data[i] = '.';
}
void display() const{
for (int i = 1; i <= size * size; ++i) {
std::cout << data[i - 1] << " ";
if (!(i % size)) std::cout << "\n";
}
}
bool getIfInDanger(Vector2 position) const {
if (position.y < 0) position.y = 0;
if (position.x < 0) position.x = 0;
if (position.y >= 20) position.y = size - 1;
if (position.x >= 20) position.x = size - 1;
return(data[position.getX() + (position.getY() * size)] == 'X');
}
void setElement(char&& asda, Vector2 position) {
data[position.getX() + (position.getY() * size)] = asda;
}
};

class Solver
{
Vector2 startPos, endPos;
std::vector<Vector2> directions;
Map map;
public:
Solver(Vector2 _startPos, Vector2 _endPos, int size) : startPos(_startPos),
endPos(_endPos){
Map temp(size);
map = temp;

map.setElement('X', Vector2(14, 15));


map.setElement('X',Vector2(15,15));
map.setElement('X', Vector2(16, 15));
map.setElement('X', Vector2(16, 14));
map.setElement('X', Vector2(16, 13));

directions.resize(8);
directions[0] = Vector2(-1, 1);
directions[1] = Vector2(-1, 0);
directions[2] = Vector2(-1, -1);
directions[3] = Vector2(0, 1);
directions[4] = Vector2(0, -1);
directions[5] = Vector2(1, 1);
directions[6] = Vector2(1, 0);
directions[7] = Vector2(1, -1);
}
bool aStar() {
Node startNode(startPos);
Node goalNode(Vector2(endPos.getX(), endPos.getY()));

if (map.getIfInDanger(startNode.position) || map.getIfInDanger(goalNode.position)) {
std::cout << "Either the start of this map is obstructed or so is the end.";
return false;
}

std::list<Node> openList;
std::list<Node> closedList;

startNode.calc(endPos);
openList.push_back(startNode);

while (!openList.empty()) {
auto current = Node(*std::min_element(openList.begin(), openList.end()));

current.calc(endPos);

closedList.push_back(current);
openList.remove(current);
if (current == goalNode) break;

for (auto& direction : directions) {


Node successor(direction + current.position);

if (map.getIfInDanger(successor.position) || successor.position.getX() > 20 - 1 ||


successor.position.getY() > 20 - 1 || successor.position.getX() < 0 ||
successor.position.getY() < 0 ||
std::find(closedList.begin(), closedList.end(), successor) != closedList.end()) {
continue;
}

successor.calc(endPos);

auto inOpen = std::find(openList.begin(), openList.end(), successor);


if (inOpen == openList.end()) {
successor.parent = &closedList.back();
successor.calc(endPos);

openList.push_back(successor);
}
else
if (successor.G < inOpen->G) successor.parent = &closedList.back();
}
}

if (!openList.size()) {
std::cout << "No path has been found\n";
return false;
}

auto inClosed = std::find(closedList.begin(), closedList.end(), goalNode);


if (inClosed != closedList.end()) {
while (*inClosed != startNode) {
map.setElement('Y',inClosed->position);
*inClosed = *inClosed->parent;
}
}

map.display();
return true;
}
};

int main()
{
Solver solve(Vector2(0,0),Vector2(19,19), 20);
solve.aStar();
}
Output: -
Experiment – 6

Aim: - Write a program to conduct game search.


#include<bits/stdc++.h>
using namespace std;
#define COMPUTER 1
#define HUMAN 2
#define SIDE 3
#define COMPUTERMOVE 'O'
#define HUMANMOVE 'X'
void showBoard(char board[][SIDE])
{
printf("\n\n");
printf("\t\t\t %c | %c | %c \n", board[0][0],board[0][1], board[0][2]);
printf("\t\t\t--------------\n");
printf("\t\t\t %c | %c | %c \n", board[1][0],board[1][1], board[1][2]);
printf("\t\t\t--------------\n");
printf("\t\t\t %c | %c | %c \n\n", board[2][0],board[2][1], board[2][2]);
return;
}
void showInstructions()
{
printf("\t\t\t Tic-Tac-Toe\n\n");
printf("Choose a cell numbered from 1 to 9 as below" " and play\n\n");
printf("\t\t\t 1 | 2 | 3 \n");
printf("\t\t\t--------------\n");
printf("\t\t\t 4 | 5 | 6 \n");
printf("\t\t\t--------------\n");
printf("\t\t\t 7 | 8 | 9 \n\n");
printf("-\t-\t-\t-\t-\t-\t-\t-\t-\t-\n\n");
return;
}
void initialise(char board[][SIDE], int moves[])
{
srand(time(NULL));
for (int i=0; i<SIDE; i++)
{
for (int j=0; j<SIDE; j++)
board[i][j] = ' ';
}
for (int i=0; i<SIDE*SIDE; i++)
moves[i] = i;
random_shuffle(moves, moves + SIDE*SIDE);
return;
}
void declareWinner(int whoseTurn)
{
if (whoseTurn == COMPUTER)
printf("COMPUTER has won\n");
else
printf("HUMAN has won\n");
return;
}
bool rowCrossed(char board[][SIDE])
{
for (int i=0; i<SIDE; i++)
{
if (board[i][0] == board[i][1] &&
board[i][1] == board[i][2] &&
board[i][0] != ' ')
return (true);
}
return(false);
}
bool columnCrossed(char board[][SIDE])
{
for (int i=0; i<SIDE; i++)
{
if (board[0][i] == board[1][i] &&
board[1][i] == board[2][i] &&
board[0][i] != ' ')
return (true);
}
return(false);
}
bool diagonalCrossed(char board[][SIDE])
{
if (board[0][0] == board[1][1] &&
board[1][1] == board[2][2] &&
board[0][0] != ' ')
return(true);

if (board[0][2] == board[1][1] &&


board[1][1] == board[2][0] &&
board[0][2] != ' ')
return(true);

return(false);
}
bool gameOver(char board[][SIDE])
{
return(rowCrossed(board) || columnCrossed(board)
|| diagonalCrossed(board) );
}
void playTicTacToe(int whoseTurn)
{
char board[SIDE][SIDE];
int moves[SIDE*SIDE];
initialise(board, moves);
showInstructions();
int moveIndex = 0, x, y;
while (gameOver(board) == false &&
moveIndex != SIDE*SIDE)
{
if (whoseTurn == COMPUTER)
{
x = moves[moveIndex] / SIDE;
y = moves[moveIndex] % SIDE;
board[x][y] = COMPUTERMOVE;
printf("COMPUTER has put a %c in cell %d\n",
COMPUTERMOVE, moves[moveIndex]+1);
showBoard(board);
moveIndex ++;
whoseTurn = HUMAN;
}
else if (whoseTurn == HUMAN)
{
x = moves[moveIndex] / SIDE;
y = moves[moveIndex] % SIDE;
board[x][y] = HUMANMOVE;
printf ("HUMAN has put a %c in cell %d\n",
HUMANMOVE, moves[moveIndex]+1);
showBoard(board);
moveIndex ++;
whoseTurn = COMPUTER;
}
}
if (gameOver(board) == false &&
moveIndex == SIDE * SIDE)
printf("It's a draw\n");
else
{
if (whoseTurn == COMPUTER)
whoseTurn = HUMAN;
else if (whoseTurn == HUMAN)
whoseTurn = COMPUTER;
declareWinner(whoseTurn);
}
return;
}
int main()
{
playTicTacToe(COMPUTER);
return (0);
}

Output: -
Experiment – 7

Aim: - Implementation of Game Search using MINIMAX Algorithm.


#include<bits/stdc++.h>
using namespace std;
int minimax(int depth, int nodeIndex, bool isMax,
int scores[], int h)
{
if (depth == h)
return scores[nodeIndex];
if (isMax)
return max(minimax(depth+1, nodeIndex*2, false, scores, h),
minimax(depth+1, nodeIndex*2 + 1, false, scores, h));
else
return min(minimax(depth+1, nodeIndex*2, true, scores, h),
minimax(depth+1, nodeIndex*2 + 1, true, scores, h));
}
int log2(int n)
{
return (n==1)? 0 : 1 + log2(n/2);
}
int main()
{
int scores[] = {3, 5, 2, 9, 12, 5, 23, 23};
int n = sizeof(scores)/sizeof(scores[0]);
int h = log2(n);
int res = minimax(0, 0, true, scores, h);
cout << "The optimal value is : " << res << endl;
return 0;
}

Output: -
Experiment – 8

Aim: - Write a program to construct a Bayesian network from given data.


#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;
// Node class for representing the nodes in the Bayesian network
class Node {
public:
string name; // Name of the node
vector<string> parents; // Parents of the node
map<string, double> probabilities; // Conditional probabilities for the node
};
// Function to create a new node with the given name and parents
Node* create_node(string name, vector<string> parents) {
Node* node = new Node();
node->name = name;
node->parents = parents;
return node;
}
// Function to add the conditional probabilities to the node
void add_probabilities(Node* node, map<string, double> probabilities) {
node->probabilities = probabilities;
}
// Function to print the Bayesian network
void print_bayesian_network(vector<Node*> nodes) {
cout << "Bayesian network:" << endl;
for (Node* node : nodes) {
cout << "Node " << node->name << endl;
cout << "Parents: ";
for (string parent : node->parents) {
cout << parent << " ";
}
cout << endl;
cout << "Probabilities:" << endl;
for (auto const& prob : node->probabilities) {
cout << prob.first << " -> " << prob.second << endl;
}
cout << endl;
}
}
int main() {
// Creating nodes
Node* A = create_node("A", {});
Node* B = create_node("B", {"A"});
Node* C = create_node("C", {"A"});
Node* D = create_node("D", {"B", "C"});
// Adding probabilities
map<string, double> probabilities_A = {{"true", 0.2}, {"false", 0.8}};
add_probabilities(A, probabilities_A);
map<string, double> probabilities_B = {{"true|true", 0.9}, {"true|false", 0.5}, {"false|true",
0.1}, {"false|false", 0.5}};
add_probabilities(B, probabilities_B);
map<string, double> probabilities_C = {{"true|true", 0.3}, {"true|false", 0.7}, {"false|true",
0.7}, {"false|false", 0.3}};
add_probabilities(C, probabilities_C);
map<string, double> probabilities_D = {{"true|true|true", 0.8}, {"true|true|false", 0.4},
{"true|false|true", 0.7}, {"true|false|false", 0.3},
{"false|true|true", 0.2}, {"false|true|false", 0.6}, {"false|false|true",
0.3}, {"false|false|false", 0.7}};
add_probabilities(D, probabilities_D);
// Creating vector of nodes
vector<Node*> nodes = {A, B, C, D};
// Printing the Bayesian network
print_bayesian_network(nodes);
return 0;
}

Output: -
Experiment – 9

Aim: - Write a program to infer from the Bayesian network.


#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <cassert>
using namespace std;
int game(int winningdoor, int selecteddoor, bool change=false) {
assert(winningdoor < 3);
assert(winningdoor >= 0);

int removeddoor = -1;


for (int i = 0; i < 3; i++) {
if (i != selecteddoor && i != winningdoor) {
removeddoor = i;
break;
}
}
if (change) {
for (int i = 0; i < 3; i++) {
if (i != selecteddoor && i != removeddoor) {
selecteddoor = i;
break;
}
}
}
return selecteddoor == winningdoor;
}
int main() {
srand(time(NULL));
vector<int> playerdoors(1000000);
for (int i = 0; i < 1000000; i++) {
playerdoors[i] = rand() % 3;
}
int winningdoors1 = 0;
int winningdoors2 = 0;
for (int i = 0; i < 1000000; i++) {
if (game(1, playerdoors[i])) {
winningdoors1++;
}
if (game(1, playerdoors[i], true)) {
winningdoors2++;
}
}
cout << "Winning percentage without changing choice: " << (double)winningdoors1 /
1000000 << endl;
cout << "Winning percentage while changing choice: " << (double)winningdoors2 /
1000000 << endl;
return 0;
}

Output: -
Experiment – 10

Aim: - Write a program to run value and policy iteration in a grid world.
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
const int rMax = 3, cMax = 4;
const double Ra = -3;
const double gamma = 1;
const double pGood = 0.8;
const double pBad = (1 - pGood) / 2;
const int N = 10000;
const double deltaMin = 1e-9;
double U[rMax][cMax];
double Up[rMax][cMax];
double R[rMax][cMax];
char Pi[rMax][cMax];
int main()
{
int r, c;
double delta = 0;
memset(Pi, 0, sizeof(Pi));
memset(Up, 0, sizeof(Up));
memset(U, 0, sizeof(U));
memset(R, Ra, sizeof(R));
R[0][3] = 100;
R[1][3] = -100;
do {
// Copy U to Up
memcpy(Up, U, sizeof(U));

// Update U
delta = 0;
for (r = 0; r < rMax; r++) {
for (c = 0; c < cMax; c++) {
double maxU = -1e9;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (abs(i) + abs(j) != 1) continue;
int rr = r + i;
int cc = c + j;
if (rr < 0 || rr >= rMax || cc < 0 || cc >= cMax) continue;
double Uc = pGood * Up[rr][cc];
if (i != 0 && j != 0) {
Uc += pBad * Up[r][cc];
Uc += pBad * Up[rr][c];
}
maxU = max(maxU, Uc);
}
}
U[r][c] = R[r][c] + gamma * maxU;
delta = max(delta, abs(U[r][c] - Up[r][c]));
}
}
} while (delta > deltaMin);

// Print final U
for (r = 0; r < rMax; r++) {
for (c = 0; c < cMax; c++) {
cout << U[r][c] << " ";
}
cout << endl;
}

return 0;
}

Output: -
Experiment – 11

Aim: - Write a program to do reinforcement learning in a grid world.


#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <pgmpy/models/BayesianModel.h>
#include <pgmpy/estimators/MaximumLikelihoodEstimator.h>
#include <pgmpy/inference/VariableElimination.h>

using namespace std;


using namespace pgmpy::models;
using namespace pgmpy::estimators;
using namespace pgmpy::inference;

int main() {

ifstream fin("heart.csv");
vector<vector<string>> data;
string line;
while (getline(fin, line)) {
vector<string> row;
string cell;
for (char c : line) {
if (c == ',') {
row.push_back(cell);
cell = "";
} else {
cell += c;
}
}
row.push_back(cell);
data.push_back(row);
}
fin.close();

for (vector<string>& row : data) {


for (string& cell : row) {
if (cell == "?") {
cell = "NaN";
}
}
}

cout << "Few examples from the dataset are given below" << endl;
for (int i = 0; i < min(5, (int)data.size()); i++) {
for (string& cell : data[i]) {
cout << cell << " ";
}
cout << endl;
}

BayesianModel model({{"age", "trestbps"}, {"age", "fbs"}, {"sex", "trestbps"}, {"exang",


"trestbps"}, {"trestbps", "heartdisease"}, {"fbs", "heartdisease"}, {"heartdisease", "restecg"},
{"heartdisease", "thalach"}, {"heartdisease", "chol"}});

cout << "\n Learning CPD using Maximum likelihood estimators" << endl;
MaximumLikelihoodEstimator estimator(model);
estimator.fit(data);

cout << "\n Inferencing with Bayesian Network:" << endl;


VariableElimination HeartDisease_infer(model);

cout << "\n 1. Probability of HeartDisease given Age=30" << endl;


map<string, int> evidence = {{"age", 28}};
DiscreteFactor q = HeartDisease_infer.query({"heartdisease"}, evidence);
cout << q << endl;

cout << "\n 2. Probability of HeartDisease given cholesterol=100" << endl;


evidence = {{"chol", 100}};
q = HeartDisease_infer.query({"heartdisease"}, evidence);
cout << q << endl;
return 0;
}

Output: -

You might also like