Sclab
Sclab
BONAFIDE CERTIFICATE
NAME
REG.NO
DEGREE & BRANCH
SUBJECT CODE & TITLE :..............................................
YEAR& SEM
Certified that this Bonafide Record of Work done by the above student of
the......................................................................................................... Laboratory
Page
S.No. Date Name of the Experiment Marks Signature
No.
EXPl Implementation of fuzzy control inference system
Date:
AIM: Understand the concept of fuzzy control inference system using python programming
language.
Algorithm:
Step 1: Define Fuzzy Sets input and output variables.
Step 2: Create Fuzzy Rules
Step 3: Perform Fuzzy Inference
Step 4: Defuzzify the output fuzzy sets to obtain a crisp output value.
Step 5: Use the defuzzified output as the control action.
Step 6: Implement Control Action.
Step 7: Repeat the above steps in a loop as needed for real-time control.
End of the fuzzy control algorithm.
First, you'll need to install the scikit-fuzzy library if you haven't already. You can install it using
the following command:
PROGRAM:
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
fan_speed.view(sim=fan_speed_ctrl)
2
3
Output:
1.0
0.8
,9- 0.6
-5;
ai -low
.c
E - medium
Q)
- high
::E 0.4
0.2
0.0 ------r--------.--------r--------,----------------------------------'1
0 20 40 60 80 100
temperature
4
1.0
-low
- medium
- high
0.8
.9- 0.6
-5;
cu
.0.
E
Cl)
:E: 0.4
0.2
0.0
0 20 40 60 80 100
fan_speed
1.0
0.8
.9- 0.6
.c -low
Vl
cu - medi m
.0.
E
Cl)
- high
:E: 0.4
0.2
0.0
0 20 40 60 80 100
fan_speed
5
6
Result: Thus the above program for fuzzy control interface system executed successfully with
desired output.
7
EXP2 Programming exercise on classification with a discrete perceptron
Date:
AIM: Understand the concept of classification with discrete perceptron using python
programming language.
Algorithm:
Step 1: Initialize weights W and bias b to small random values
Step 2: Define learning rate
Step 3: Define the number of training epochs
Step 4: Define the training data (features and labels
Step 5: Define the perceptron training algorithm
Step 6: The perceptron is now trained, and you can use it to make predictions
PROGRAM:
import numpy as np
class DiscretePerceptron:
def _init_(self, input_size):
self.weights= np.zeros(input_size)
self.bias = 0
def main():
# Generate some example data points for two classes
class_0 = np.array([[2, 3], [3, 2], [1, l]])
class_l = np.array([[5, 7], [6, 8], [7, 6]])
# Combine the data points and create labels (0 for class 0, 1 for class 1)
inputs= np.vstack((class_0, class_l))
targets= np.array([0, 0, 0, 1, 1, 1])
8
# Create a discrete perceptron with input size 2
perceptron = DiscretePerceptron(input_size=2)
# Test the trained perceptron with new data
test_data = op.array([[ 4, 5], [2, 2]])
for data in test_data:
prediction= perceptron.predict(data)
if prediction == 0:
print(f"Data {data} belongs to class O")
else:
print(f"Data {data} belongs to class l ")
if _name_== "_main_"·
main()
9
Output:
10
Result: Thus the above program classification with discrete perceptron executed successfully
with desired output.
11
EXP3 Implementation of XOR with backpropagation algorithm
Date:
AIM: Understand the concept of XOR with backpropagation algorithm using python
programing language.
Algorithm:
1. Initialize the neural network with random weights and biases.
2. Define the training data for XOR
3. Set hyperparameters:
Learning rate (alpha)
Number of epochs (iterations)
Number of hidden layers and neurons per layer
Activation function (e.g., sigmoid)
4. Repeat for each epoch:
a. Initialize the total error for this epoch to 0.
b. For each training example in the dataset:
1. Forward propagation:
Compute the weighted sum of inputs and biases for each neuron in the
hidden layer(s) and output layer.
Apply the activation function to each neuron's output.
11. Compute the error between the predicted output and the actual output for the
current training example.
iii. Update the total error for this epoch with the squared error from step ii.
iv. Backpropagation:
Compute the gradient of the error with respect to the output layer neurons.
Backpropagate the gradients through the hidden layers.
Update the weights and biases using the gradients and the learning rate.
c. Calculate the average error for this epoch by dividing the total error by the number of
training examples.
d. Check if the average error is below a predefined threshold or if the desired accuracy
is reached.
- If yes, exit the training loop.
5. Once training is complete, you can use the trained neural network to predict XOR values
for new inputs.
6. End.
PROGRAM:
import numpy as np
12
def sigmoid_derivative(x):
return x * (1 - x)
# Training loop
for _ in range(epochs):
# Forward propagation
hidden_layer_activation = np.dot(input_data, hidden_weights)
hidden_layer_output = sigmoid(hidden_layer_activation)
# Calculate error
error = target_data - predicted_output
# Backpropagation
output_delta = error * sigmoid_derivative(predicted_output)
hidden_layer_error = output_delta.dot(output_weights.T)
hidden_layer_delta = hidden_layer_error * sigmoid_derivative(hidden_layer_output)
# Update weights
output_weights += hidden_layer_output.T.dot(output_delta) * learning_rate
hidden_weights += input_data.T.dot(hidden_layer_delta) * learning_rate
13
Output:
14
Result: Thus the above program classification with discrete perception executed successfully
with desired output.
15
EXP4 Implementation of self-organizing maps for a specific application.
Date:
AIM: Understand the concept of self-organizing maps for a specific application using
python programming language.
Algorithm:
4. Repeat the training process until convergence (or a predetermined number of epochs).
6. Visualization (optional):
- Visualize the trained SOM grid to understand the data distribution and clustering.
PROGRAM:
import numpy as np
import matplotlib.pyplot as plt
16
#
Generate some sample data (replace this with your own dataset)
# SOM parameters
grid_size = (10, 10) # Grid size of the SOM
input_dim = 2 # Dimensionality of the input data
learning_rate = 0.2
num_epochs = 1000
# Training loop
for epoch in range(num_epochs):
for input_vector in data:
# Find the Best Matching Unit (BMU)
distances = np.linalg.norm(weight_matrix - input_vector, axis=-1)
bmu_coords = np.unravel_index(np.argmin(distances), distances.shape)
17
Output:
88
86
84
82
;;]J
,bJ
tl'J
3
0
80
78
76
74
18
Result: Thus the above program for self-organizing map executed successfully with desired
output
19
EXP 5 Programming exercises on maximizing a function using Genetic algorithm.
Date:
AIM: Understand the concept of maximizing function using Genetic algorithm using python
programming.
Algorithm:
1. Initialize the population with random solutions.
2. Define the fitness function to evaluate how good each solution is.
3. Set the maximum number of generations.
4. Set the mutation rate (probability of changing a gene in an individual).
5. Set the crossover rate (probability of two individuals mating).
6. Repeat for each generation:
a. Evaluate the fitness of each individual in the population using the fitness function.
b. Select the best individuals based on their fitness to become parents.
c. Create a new generation by crossover (mixing) the genes of the parents.
d. Apply mutation to some individuals in the new generation.
e. Replace the old population with the new generation.
7. Repeat for the specified number of generations.
8. Find and return the individual with the highest fitness as the best solution.
PROGRAM:
import random
20
# Perform crossover to create a new generation
def crossover(parentl, parent2, crossover_prob=0.7):
if random.random() < crossover_prob:
crossover_point = random.randint(1, 1) # Corrected this line
childl = (parentl + parent2) / 2
child2 = (parentl + parent2) / 2
return child1, child2
else:
# Genetic Algorithm
def genetic_algorithm(generations, pop_size, lower_bound, upper_bound):
population = initialize_population(pop_size, lower_bound, upper_bound)
population = new_population
if _name_== "_main_":
generations = 50
pop_size = 100
lower_bound = -10
upper_bound = 10
21
Output:
22
Result: Thus the above program maximizing function using genetic algorithm executed
successfully with desired output.
23
EXP6 Implementation of two input sine function.
Date:
AIM: Understand the concept of implementation of two input sine function using Genetic
algorithm.
Algorithm:
# Genetic Algorithm for Two-Input Sine Function Optimization
1. Define the fitness function
2. Initialize the population
3. Define functions for genetic operations
4. Implement the main genetic algorithm loop
5. Print the final best solution found by the genetic algorithm.
PROGRAM
import random
import math
24
else:return parentl, parent2
# Genetic Algorithm
def genetic_algorithm(generations, pop_size, lower_bound, upper_bound):
population = initialize_population(pop_size, lower_bound, upper_bound)
population = new_population
if _name_== "_main_"·
generations = 50
pop_size = 100
lower_bound = -2 * math.pi
upper_bound = 2 * math.pi
25
Output:
Generation 1: Best individual - (-5.806639394411164, 2.957052015269947), Fitness -
0.6422076600091893
Generation 2: Best individual - (-3.7004701839702663, 4.4413546380285975), Fitness - -
0.43325964387284566
Generation 3: Best individual - (-3.7004701839702663, 5.464316418988149), Fitness
0.20013884834113005
Generation 4: Best individual - (5.481791654037208, 3.3095163097626763), Fitness
0.8854619344317294
Generation 5: Best individual - (4.897491323013819, 3.3095163097626763), Fitness
1.150052992911647
Generation 6: Best individual - (4.976671184995054, 3.3095163097626763), Fitness
1.1324158225088536
Generation 7: Best individual - (3.9420165382340246, 3.3095163097626763), Fitness
0.8847869227205696
Generation 8: Best individual - (4.198534144176835, 5.481189847293816), Fitness
1.5896010966615468
Generation 9: Best individual - (4.198534144176835, 5.481189847293816), Fitness
1.5896010966615468
Generation 10: Best individual - (4.198534144176835, 5.481189847293816), Fitness
1.5896010966615468
Generation 11: Best individual - (4.34542752972704, 5.481189847293816), Fitness
l.6521667383260996
Generation 12: Best individual - (-1.2170450032547304, 5.481189847293816), Fitness
1.6568246976897136
Generation 13: Best individual - (-l.2185577577082327, 5.481189847293816), Fitness
1.6573476714317006
Generation 14: Best individual - (-l.2170450032547304, 5.481189847293816), Fitness
1.6568246976897136
Generation 15: Best individual - (-l .2170450032547304, 5.481189847293816), Fitness
1.6568246976897136
Generation 16: Best individual - (-l .2170450032547304, 5.481189847293816), Fitness
1.6568246976897136
Generation 17: Best individual - (-l .2170450032547304, 5.481189847293816), Fitness
1.6568246976897136
Generation 18: Best individual - (-1.2170450032547304, 5.481189847293816), Fitness
1.6568246976897136
Generation 19: Best individual - (-l.2185577577082327, 5.481189847293816), Fitness
l.6573476714317006
Generation 20: Best individual - (4.266603727856264, 5.481189847293816), Fitness - -
1.621017281069609
Generation 21: Best individual - (-l.2170450032547304, 5.481189847293816), Fitness
1.6568246976897136
Generation 22: Best individual - (-l.2170450032547304, 5.481189847293816), Fitness
1.6568246976897136
Generation 23: Best individual - (4.976671184995054, 5.481189847293816), Fitness
1.6840251615701645
Generation 24: Best individual - (4.897491323013819, 5.481189847293816), Fitness
26
1.7016623319729578
Generation 25: Best individual - (-l.2185577577082327, 5.481189847293816), Fitness
1.6573476714317006
Generation 26: Best individual - (-l.2185577577082327, 5.481189847293816), Fitness
l.6573476714317006
Generation 27: Best individual - (-l.2185577577082327, 5.481189847293816), Fitness
l.6573476714317006
27
Result: Thus the above program implementation of two input sine function using genetic
algorithm executed successfully.
28
EXP7 Implementation of three input nonlinear function
Date:
AIM
Algorithm
# Genetic Algorithm for Three-Input Nonlinear Function Optimization
1. Define the fitness function.
2. Initialize the population.
3. Define functions for genetic operations.
4. Implement the main genetic algorithm loop.
5. Print the final best solution found by the genetic algorithm.
PROGRAM
import random
29
child2 = (crossover_point2 * parentl [0] + (1 - crossover_point2) *
parent2[0], crossover_point2 * parentl [l] + (1 - crossover_point2) *
parent2[1],crossover_point2 * parentl [2] + (1 - crossover_point2) * parent2[2])
return child1, child2
else:
return parentl, parent2
# Genetic Algorithm
def genetic_algorithm(generations, pop_size, lower_bound, upper_bound):
population = initialize_population(pop_size, lower_bound, upper_bound)
population = new_population
if _name_ _main_"·
import math
generations= 50
pop_size = 100
lower_bound = -1
upper_bound = 1
32
Result: Thus the above program genetic algorithm for three input non-linear function optimization
executed successfully.
33