ALML LAB 2021 REGULATION 1 Nidharsanaa1
ALML LAB 2021 REGULATION 1 Nidharsanaa1
AIM:
ALGORITHM:
1. Create an empty queue (for BFS) or stack (for DFS) and add the initial state to it.
2. Create an empty set to store visited states.
3. While the queue (or stack) is not empty:
Remove the first state from the queue (or the last state from the stack).
If the state is the goal state, return the path from the initial state to the current
state.
Otherwise, generate all possible actions from the current state.
For each action, generate the resulting state and check if it has been visited before.
If it has not been visited, add it to the queue (or stack) and mark it as visited.
4. If the queue (or stack) is empty and no goal state has been found, return failure.
1
PROGRAM:
2
OUTPUT :
RESULT:-
Thus the python program for uninformed search algorithms (BFS, DFS) has been written
and executed successfully
3
Ex. No:2A IMPLEMENTATION OF INFORMED SEARCH
ALGORITHMS A*
DATE:
AIM:
Aim is to write a program in python to solve problems by using Implementation of
Informed search algorithms A*
ALGORITHM:
2. Add the initial state to the open set with a cost of 0 and an estimated total cost (f-score) of the
heuristic value of the initial state.
4.If the open set is empty and no goal state has been found, return failure.
4
PROGRAM :
aStarAlgo('A', 'J')
6
OUTPUT :
Path found: ['A', 'F', 'G', 'I', 'J']
RESULT:
Thus the python program for informed search algorithm A* search has been
written and executed successfully
7
EX. NO:2B
INFORMED SEARCH ALGORITHMS MEMORY-
DATE:
BOUNDED A*
AIM:
Aim is to write a program in python to solve problems by using Implementation of
Informed search algorithms memory-bounded A*
ALGORITHM:
8
PROGRAM :
_, current_node = frontier.get()
if current_node == goal_node:
path = []
while current_node != start_node:
path.append(current_node)
current_node = current_node.parent
path.append(start_node)
path.reverse()
return path
explored.add(current_node)
return None
class Node:
def __init__(self, state, parent=None):
self.state = state
self.parent = parent
self.cost = 1
9
def __eq__(self, other):
return self.state == other.state
def __hash__(self):
return hash(self.state)
def children(self):
# Generates all possible children of a given node
children = []
for action in [-1, 1]:
child_state = self.state + action
child_node = Node(child_state, self)
children.append((child_node, child_node.cost))
return children
# Example usage
start_node = Node(1)
goal_node = Node(10)
10
OUTPUT :
RESULT:
Thus the python program for informed search algorithms bounded A* has been written
and executed successfully
11
EX.NO:3A IMPLEMENT NAIVE BAYES MODELS
(GAUSSIAN NAIVE BAYES)
DATE:
AIM:
Aim is to write a program in python to solve problems by using Implement naive Bayes
model (Gaussian Naive Bayes)
ALGORITHM:
Input:
• Training dataset with features X and corresponding labels Y
• Test dataset with features X_test
Output:
• Predicted labels for test dataset Y_pred
Steps:
1. Calculate the prior probabilities of each class in the training dataset, i.e., P(Y = c), where c is
the class label.
2. Calculate the mean and variance of each feature for each class in the training dataset.
3. For each test instance in X_test, calculate the posterior probability of each class c, i.e., P(Y = c
| X = x_test), using the Gaussian probability density function: P(Y = c | X = x_test) = (1 /
(sqrt(2*pi)*sigma_c)) * exp(-((x_test - mu_c)^2) / (2 * sigma_c^2)) where mu_c and sigma_c
are the mean and variance of feature values for class c, respectively.
4. For each test instance in X_test, assign the class label with the highest posterior probability as
the predicted label Y_pred.
12
PROGRAM :
# Print results
print("Accuracy:", accuracy)
13
OUTPUT :
Accuracy: 1.0
RESULT:
Thus the python program for Gaussian Naive Bayes has been written and executed
successfully
14
EX. NO:3B IMPLEMENT NAIVE BAYES MODELS
(MULTINOMIAL NAIVE BAYES)
DATE:
AIM:
Aim is to write a program in python to solve problems by using Implement naive Bayes
model (Multinomial Naive Bayes)
ALGORITHM:
1. Convert the training dataset into a frequency table where each row represents a
document, and each column represents a word in the vocabulary. The values in the table
represent the frequency of each word in each document.
2. Calculate the prior probabilities of each class label by dividing the number of documents
in each class by the total number of documents.
3. Calculate the conditional probabilities of each word given each class label. This involves
calculating the frequency of each word in each class and dividing it by the total number
of words in that class.
4. For each document in the test dataset, calculate the posterior probability of each class
label using the Naive Bayes formula:
6. where word1, word2, ..., wordn are the words in the document and P(word | class_label)
is the conditional probability of that word given the class label.
7. Predict the class label with the highest posterior probability for each document in the test
dataset.
15
PROGRAM :
# Fit the vectorizer to the training data and transform the data
train_features = vectorizer.fit_transform(train_data)
# Create a Multinomial Naive Bayes classifier and train it on the training data
clf = MultinomialNB()
clf.fit(train_features, train_labels)
# Use the trained classifier to predict the class labels for the test data
predicted_labels = clf.predict(test_features)
16
OUTPUT :
['negative' 'negative']
RESULT:
Thus the python program for Multinomial Naive Bayes has been written and executed
successfully
17
EX.NO: 4 IMPLEMENT BAYESIAN
DATE: NETWORKS
AIM:
Aim is to write a program in python to solve problems by using Implement Bayesian
Networks.
ALGORITHM:
18
PROGRAM:
# Perform variable elimination to compute the probability of getting a good letter given high
intelligence and low difficulty
inference = VariableElimination(model)
query = inference.query(variables=['Letter'], evidence={'Intelligence': 1, 'Difficulty': 0},
show_progress=False)
print("P(Letter=Good | Intelligence=High, Difficulty=Low) =", query.values[0])
19
OUTPUT :
RESULT:
Thus the python program for Bayesian Networks has been written and executed
successfully
20
EX. NO: 5 BUILD REGRESSION MODELS
DATE:
AIM:
To write a python program to solve Build Regression Models
ALGORITHM:
21
PROGRAM:
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
# Load data
data = pd.read_csv('data.csv')
# Evaluate model
train_pred = reg.predict(X_train)
test_pred = reg.predict(X_test)
print('Train MSE:', mean_squared_error(y_train, train_pred))
print('Test MSE:', mean_squared_error(y_test, test_pred))
22
OUTPUT:
RESULT:
Thus the python program for regression models has been written and executed
successfully
23
EX. NO: 6A
BUILD DECISION TREES
DATE:
AIM:
To write a python program to solve Build decision trees
ALGORITHM:
Choose a feature that provides the most information gain (reduces uncertainty)
Split the dataset based on the selected feature
24
PROGRAM:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
25
OUTPUT:
RESULT:
Thus the python program for decision trees has been written and executed successfully
26
EX. NO: 6B
BUILD RANDOM FORESTS
DATE:
AIM:
To write a python program to solve Build random forests
ALGORITHM:
For a new data point, pass it through each tree in the forest
Aggregate the predictions of all trees (e.g., by majority vote)
27
PROGRAM:
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
28
OUTPUT:
Random Forest Accuracy: 1.0
RESULT:-
Thus the python program for random forests has been written and executed successfully
29
EX. NO: 7 BUILD SVM MODELS
DATE:
AIM:
To write a python program to solve Build SVM Model’s
ALGORITHM:
c. Specify the gamma value (if applicable) 5. Train the SVM model using the training data
30
PROGRAM :
31
OUTPUT:
Accuracy: 1.0
RESULT:-
Thus the python program for SVM models has been written and executed successfully
32
EX. NO: 8 IMPLEMENT ENSEMBLING TECHNIQUES
DATE:
AIM:
To write a python program to solve Implement ensembling techniques
ALGORITHM:
1. Load the breast cancer dataset and split the data into training and testing sets using
train_test_split() function.
2. Train 10 random forest models using bagging by randomly selecting 50% of the training
data for each model, and fit a random forest classifier with 100 trees to the selected data.
3. Test each model on the testing set and calculate the accuracy of each model using
accuracy_score() function.
4. Combine the predictions of the 10 models by taking the average of the predicted
probabilities for each class, round the predicted probabilities to the nearest integer, and
calculate the accuracy of the ensemble model using accuracy_score() function.
5. Print the accuracy of each individual model and the ensemble model.
33
PROGRAM:
data = load_breast_cancer()
X = data.data
y = data.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
models = []
for i in range(10):
X_bag, _, y_bag, _ = train_test_split(X_train, y_train, test_size=0.5)
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_bag, y_bag)
y_pred = model.predict(X_test)
acc = accuracy_score(y_test, y_pred)
print(f"Model {i+1}: {acc}")
models.append(model)
y_preds = []
for model in models:
y_pred = model.predict(X_test)
y_preds.append(y_pred)
y_ensemble = sum(y_preds) / len(y_preds)
y_ensemble = [int(round(y)) for y in y_ensemble]
acc_ensemble = accuracy_score(y_test, y_ensemble)
print(f"Ensemble: {acc_ensemble}")
34
OUTPUT:
Model 1: 0.9649122807017544
Model 2: 0.9473684210526315
Model 3: 0.956140350877193
Model 4: 0.9649122807017544
Model 5: 0.956140350877193
Model 6: 0.9649122807017544
Model 7: 0.956140350877193
Model 8: 0.956140350877193
Model 9: 0.956140350877193
Model 10: 0.9736842105263158
Ensemble: 0.956140350877193
RESULT:-
Thus the python program for ensembling techniques has been written and executed
successfully
35
EX. NO: 9A IMPLEMENT CLUSTERING ALGORITHMS
DATE: (HIERARCHICAL CLUSTERING )
AIM:
To write a python program to solve Implement clustering algorithms (Hierarchical
clustering)
ALGORITHM:
36
PROGRAM:
import numpy as np
from scipy.cluster.hierarchy import dendrogram, linkage
import matplotlib.pyplot as plt
# Plot dendrogram
plt.figure(figsize=(10, 5))
dendrogram(Z)
plt.show()
37
OUTPUT:
RESULT:-
Thus the python program for Hierarchical clustering has been written and
executed successfully.
38
EX. NO: 9B
IMPLEMENT CLUSTERING ALGORITHMS
DATE: (DENSITY-BASED CLUSTERING)
AIM:
To write a python program to solve Implement clustering algorithms (Density-based
clustering)
ALGORITHM:
39
PROGRAM:
40
OUTPUT:
RESULT:-
Thus the python program has Density-based clustering been written and executed
successfully.
41
EX. NO: 10 IMPLEMENT EM FOR BAYESIAN NETWORKS
DATE:
AIM:
To write a python program to solve Implement EM for Bayesian networks
ALGORITHM:
1. Define the structure of the Bayesian network
2. Define the parameters of the network, such as the conditional probability tables (CPDs)
3. Generate some synthetic data for the network
4. Initialize the model parameters using maximum likelihood estimation
5. Repeat the following steps until convergence or a maximum number of iterations is
reached:
a) E-step: compute the expected sufficient statistics of the hidden variables given the
observed data and the current estimates of the parameters
b) M-step: update the parameters to maximize the expected log-likelihood of the
observed data under the current estimate of the hidden variables
6. Print the learned parameters
42
PROGRAM:
from pgmpy.models import BayesianModel
from pgmpy.estimators import MaximumLikelihoodEstimator
from pgmpy.inference import VariableElimination
import numpy as np
43
OUTPUT :
╒═════╤═══════╕
│ C_0 │ 0.686 │
├─────┼───────┤
│ C_1 │ 0.314 │
╘═════╧═══════╛
╒═════╤═════╤═════╕
│ C │ C_0 │ C_1 │
├─────┼─────┼─────┤
│ F_0 │ 0.8 │ 0.3 │
├─────┼─────┼─────┤
│ F_1 │ 0.2 │ 0.7 │
╘═════╧═════╧════
RESULT:
Thus the python program for EM for Bayesian networks has been written and executed
successfully.
44
EX. NO: 11 BUILD SIMPLE NN MODELS
DATE:
AIM:
To write a python program to solve Build simple NN models
ALGORITHM:
1. Import necessary libraries:
i. Numpy for handling arrays and mathematical operations
ii. Keras for building and training neural networks
2. Define the input and output data:
i. Create a simple dataset using NumPy arrays
ii. Define the input data as a 2D array with four rows and two columns
iii. Define the output data as a 1D array with four elements
3. Define the neural network model:
i. Create a sequential model using Keras
ii. Add a dense layer with 4 neurons and the ReLU activation function
iii. Add another dense layer with a single neuron and the sigmoid activation function
4.Compile the neural network model:
i. Define the loss function as binary cross-entropy
ii. Define the optimizer as Adam
iii. Specify the evaluation metric as accuracy
5.Train the neural network model:
i. Call the fit() method on the model with the input and output data as arguments
ii. Specify the number of epochs as 1000 and the batch size as 4
iii. Set the verbose parameter to 0 to suppress output
6. Test the neural network model:
i. Define the test data as a 2D array with the same format as the input data
ii. Call the predict() method on the model with the test data as an argument
iii. Print the output predictions
7. End of the program.
45
PROGRAM :
import numpy as np
y = np.array([0, 1, 1, 0])
model = Sequential()
model.add(Dense(1, activation='sigmoid'))
predictions = model.predict(test_data)
print(predictions)
46
OUTPUT:
[[0.5]
[0.5]
[0.5]
[0.5]]
RESULT:
Thus the python program for EM for Bayesian networks has been written and executed
successfully.
47
EX. NO: 12
BUILD DEEP LEARNING NN MODELS
DATE:
AIM:
To write a python program to solve Build deep learning NN models
ALGORITHM:
1. Load the MNIST dataset using mnist.load_data() from the keras.datasets module.
2. Preprocess the data by reshaping the input data to a 1D array, converting the data type to
float32, normalizing the input data to values between 0 and 1, and converting the target
variable to categorical using np_utils.to_categorical().
3. Define the neural network architecture using the Sequential() class from Keras. The
model should have an input layer of 784 nodes, two hidden layers of 512 nodes each with
ReLU activation and dropout layers with a rate of 0.2, and an output layer of 10 nodes
with softmax activation.
4. Compile the model using compile() with 'categorical_crossentropy' as the loss
function, 'adam' as the optimizer, and 'accuracy' as the evaluation metric.
5. Train the model using fit() with the preprocessed training data, the batch size of 128, the
number of epochs of 10, and the validation data. Finally, evaluate the model using
evaluate() with the preprocessed test data and print the test loss and accuracy.
48
PROGRAM:
import numpy as np
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.utils import np_utils
# Convert data type to float32 and normalize the input data to values between 0 and 1
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
49
OUTPUT:
RESULT:
Thus the python program for deep learning NN models has been written and executed
successfully
50