Soft Computing Lab Record
Soft Computing Lab Record
No:01
Date: Implementation of fuzzy control inference system
AIM:
Understand the concept of fuzzy control inference system using python programming language.
ALGORITHM:
PROGRAM:
import numpy as np
import skfuzzy as fuzz from skfuzzy import control as ctrl
1
# Define fuzzy rules
rule1 = ctrl.Rule(temperature['low'], fan_speed['low'])
rule2=ctrl.Rule(temperature['medium'],fan_speed['medium'])
rule3 = ctrl.Rule(temperature['high'], fan_speed['high'])
2
OUTPUT:
RESULT:
Thus the above program for fuzzy control interface system executed successfully with
desired output.
3
Exp.No:02 Programming exercise on classification
Date: with a discrete perceptron
AIM:
Understand the concept of classification with discrete perceptron using python programming
language.
ALGORITHM:
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, 1]])
class_1 = np.array([[5, 7], [6, 8], [7, 6]])
# Combine the data points and create labels (0 for class 0, 1 for class 1)
4
inputs = np.vstack((class_0, class_1))
targets = np.array([0, 0, 0, 1, 1, 1])
if __name__ == "__main__":
main()
OUTPUT:
RESULT:
Thus the above program classification with discrete perceptron executed successfully with desired
output.
5
Exp.No: 03
Date: Implementation of XOR with backpropagation algorithm
AIM:
Understand the concept of XOR with backpropagation algorithm using python programing
language.
ALGORITHM:
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.
6
PROGRAM:
import numpy as np
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
7
# Test the trained network
test_data = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
for data in test_data:
hidden_layer_activation = np.dot(data, hidden_weights)
hidden_layer_output = sigmoid(hidden_layer_activation)
Output:
Input:[00]PredictedOutput:0.287381655624125
Input:[01]PredictedOutput:0.6696713061093961
Input:[10]PredictedOutput:0.6697648563700653
Input:[11]PredictedOutput:0.42466198065447125
RESULT:
Thus the above program classification with discrete perception executed successfully with desired
output.
8
Exp.No:04
Date: Implementation of self-organizing maps for a specific
application.
AIM:
Understand the concept of self-organizing maps for a specific application using python programming
language.
ALGORITHM:
9
PROGRAM:
import numpy as np
import matplotlib.pyplot as plt
# Generate some sample data (replace this with your own dataset)
np.random.seed(42)
data = np.random.rand(100, 2)
# 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
# Initialize the SOM
weight_matrix = np.random.rand(grid_size[0], grid_size[1], input_dim)
# 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)
# Update the BMU and its neighbors
for i in range(grid_size[0]):
for j in range(grid_size[1]):
distance_to_bmu = np.linalg.norm(np.array([i, j]) - np.array(bmu_coords))
influence = np.exp(-distance_to_bmu**2 / (2 * (epoch + 1)**2)) # Adjusting the
influence based on the current epoch
weight_matrix[i, j] += influence * learning_rate * (input_vector - weight_matrix[i, j])
# Create a map of cluster assignments
cluster_map = np.zeros((grid_size[0], grid_size[1]), dtype=int)
for i in range(grid_size[0]):
for j in range(grid_size[1]):
distances = np.linalg.norm(data - weight_matrix[i, j], axis=-1)
cluster_map[i, j] = np.argmin(distances)
# Visualize the results
plt.figure(figsize=(8, 8))
plt.pcolormesh(cluster_map, cmap='viridis')
plt.colorbar(label='Cluster')
plt.scatter(data[:, 0] * grid_size[0], data[:, 1] * grid_size[1], color='red', label='Data points')
10
plt.legend()
plt.title('Self-Organizing Map Clustering')
plt.show()
OUTPUT:
RESULT:
Thus the above program for self-organizing map executed successfully with desired output
11
Exp.No:05
Date: Programming exercises on maximizing a function using
Genetic algorithm.
AIM:
Understand the concept of maximizing function using Genetic algorithm using python programming
ALGORITHM:
Define the fitness function to evaluate how good each solution is.
a. Evaluate the fitness of each individual in the population using the fitness function.
Find and return the individual with the highest fitness as the best solution.
12
PROGRAM:
import random
# Define the fitness function (our objective function to maximize)
def fitness_function(x):
return -x**2 + 6*x + 9
# Initialize the population
def initialize_population(pop_size, lower_bound, upper_bound):
return [random.uniform(lower_bound, upper_bound) for _ in range(pop_size)]
# Select parents based on their fitness
def select_parents(population):
total_fitness = sum(fitness_function(individual) for individual in population)
roulette_wheel = [fitness_function(individual) / total_fitness for individual in population]
parent1 = random.choices(population, weights=roulette_wheel)[0]
parent2 = random.choices(population, weights=roulette_wheel)[0]
return parent1, parent2
# Perform crossover to create a new generation
def crossover(parent1, parent2, crossover_prob=0.7):
if random.random() < crossover_prob:
# Correct crossover logic
crossover_point = random.uniform(0, 1) # Random point between 0 and 1
child1 = crossover_point * parent1 + (1 - crossover_point) * parent2
child2 = crossover_point * parent2 + (1 - crossover_point) * parent1
return child1, child2
else:
return parent1, parent2
# Perform mutation in the population
def mutate(individual, mutation_prob=0.01):
if random.random() < mutation_prob:
individual += random.uniform(-1, 1)
return individual
# Genetic Algorithm
def genetic_algorithm(generations, pop_size, lower_bound, upper_bound):
population = initialize_population(pop_size, lower_bound, upper_bound)
for gen in range(generations):
new_population = []
while len(new_population) < pop_size:
parent1, parent2 = select_parents(population)
child1, child2 = crossover(parent1, parent2)
child1 = mutate(child1)
child2 = mutate(child2)
new_population.extend([child1, child2])
population = new_population
best_individual = max(population, key=fitness_function)
print(f"Generation {gen+1}: Best individual - {best_individual}, Fitness -
{fitness_function(best_individual)}")
return max(population, key=fitness_function)
13
if __name__ == "__main__":
generations = 50
pop_size = 100
lower_bound = -10
upper_bound = 10
best_solution = genetic_algorithm(generations, pop_size, lower_bound, upper_bound)
print(f"Best solution found: {best_solution}, Fitness: {fitness_function(best_solution)}")
Output:
Generation1:Bestindividual -1.338221851975824,Fitness-15.23849338674934
Generation2:Bestindividual --4.617497504442627,Fitness --40.02626823018966
Generation3:Bestindividual --6.0365409961964005,Fitness --63.65907317593823
Generation4:Bestindividual--6.086873542143298,Fitness--64.57127077090388
Generation5:Bestindividual --7.73134856380424,Fitness --97.16184199786333
Generation6:Bestindividual --8.010012301451464,Fitness --103.22037087811256
Generation7:Bestindividual --8.128709772289175,Fitness --105.84818119584459
Generation8:Bestindividual --8.128709772289175,Fitness --105.84818119584459
Generation9:Bestindividual --8.106182932958884,Fitness --105.3472993403472
Generation10:Bestindividual --8.4253359573576,Fitness --112.53830173848851
Generation11:Bestindividual --8.339831707745882,Fitness --110.59178315999888
Generation12:Bestindividual --8.511740621618573,Fitness --114.52017213942318
Generation13:Bestindividual --8.562519336850656,Fitness --115.69185341504533
Generation14:Bestindividual --8.475270784635734,Fitness --113.68183958071442
Generation15:Bestindividual --7.799825444300792,Fitness --98.63622962736679
Generation16:Bestindividual --7.799825444300792,Fitness --98.63622962736679
Generation17:Bestindividual --8.23641044465958,Fitness --108.25691968085488
Generation18:Bestindividual --8.469625574063269,Fitness --113.55231080920618
Generation19:Bestindividual --8.005479094012971,Fitness --103.12057008875657
Generation20:Bestindividual --8.331329932705664,Fitness --110.39903804383135
Generation21:Bestindividual --8.483646271761524,Fitness --113.87413169494235
Generation22:Bestindividual--8.512424180517046,Fitness--114.53591051215358
Generation23:Bestindividual --8.512424180517046,Fitness --114.53591051215358
Generation24:Bestindividual --8.536034194890835,Fitness --115.08008494569063
Generation25:Bestindividual--8.58733120697589,Fitness--116.26624450015733
Generation26:Bestindividual --7.932088839364656,Fitness --101.51056639176127
Generation27:Bestindividual --7.932088839364656,Fitness --101.51056639176127
Generation28:Bestindividual --8.633557704228673,Fitness --117.33966485761832
Generation29:Bestindividual --8.500839675355433,Fitness --114.26931323822967
Generation30:Bestindividual --8.663730407782117,Fitness --118.04260702542118
RESULT:
Thus the above program maximizing function using genetic algorithm executed successfully with
desired output.
14
Exp.No:06
Date: Implementation of two input sine function
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
# Genetic Algorithm
def genetic_algorithm(generations, pop_size, lower_bound, upper_bound):
population = initialize_population(pop_size, lower_bound, upper_bound)
for gen in range(generations):
new_population = []
while len(new_population) < pop_size:
parent1, parent2 = select_parents(population)
child1, child2 = crossover(parent1, parent2)
child1 = mutate(child1)
child2 = mutate(child2)
new_population.extend([child1, child2])
population = new_population
best_individual = max(population, key=lambda ind: fitness_function(*ind))
print(f"Generation {gen+1}: Best individual - {best_individual}, Fitness -
{fitness_function(*best_individual)}")
return max(population, key=lambda ind: fitness_function(*ind))
if __name__ == "__main__":
generations = 50
pop_size = 100
lower_bound = -2 * math.pi
upper_bound = 2 * math.pi
best_solution = genetic_algorithm(generations, pop_size, lower_bound, upper_bound)
print(f"Best solution found: {best_solution}, Fitness: {fitness_function(*best_solution)}")
16
OUTPUT:
Generation 1: Best individual - (-4.774458287427317, -4.776100739600394), Fitness -
1.9960454112384536
Generation 2: Best individual - (-4.774458287427317, -4.776100739600394), Fitness -
1.9960454112384536
Generation 3: Best individual - (-4.774458287427317, -4.748785126215906), Fitness -
1.9974120523172019
Generation 4: Best individual - (-4.774458287427317, -4.748785126215906), Fitness -
1.9974120523172019
Generation 5: Best individual - (-4.774458287427317, -4.748785126215906), Fitness -
1.9974120523172019
Generation 6: Best individual - (-4.774458287427317, -4.748785126215906), Fitness -
1.9974120523172019
Generation 7: Best individual - (-4.774458287427317, -4.776100739600394), Fitness -
1.9960454112384536
Generation 8: Best individual - (-4.774458287427317, -4.776100739600394), Fitness -
1.9960454112384536
Generation 9: Best individual - (-4.774458287427317, -4.748785126215906), Fitness -
1.9974120523172019
Generation 10: Best individual - (-4.774458287427317, -4.776100739600394), Fitness -
1.9960454112384536
Generation 11: Best individual - (-4.707765287142362, -4.748785126215906), Fitness -
1.9993270441461817
Generation 12: Best individual - (-4.752999807420658, -4.776100739600394), Fitness -
1.9971465860084108
Generation 13: Best individual - (-4.707765287142362, -4.776100739600394), Fitness -
1.9979604030674336
Generation 14: Best individual - (-4.707765287142362, -4.776100739600394), Fitness -
1.9979604030674336
Generation 15: Best individual - (-4.774458287427317, -4.748785126215906), Fitness -
1.9974120523172019
Generation 16: Best individual - (-4.765497117149649, -4.776100739600394), Fitness -
1.99656118665295
Generation 17: Best individual - (-4.774458287427317, -4.776100739600394), Fitness -
1.9960454112384536
Generation 18: Best individual - (-4.774458287427317, -4.6866992525099), Fitness -
1.997744356008841
Generation 19: Best individual - (-4.774458287427317, -4.776100739600394), Fitness -
1.9960454112384536
Generation 20: Best individual - (-4.774458287427317, -4.748785126215906), Fitness -
1.9974120523172019
Generation 21: Best individual - (-4.774458287427317, -4.6866992525099), Fitness -
1.997744356008841
Generation 22: Best individual - (-4.774458287427317, -4.6866992525099), Fitness -
1.997744356008841
Generation 23: Best individual - (-4.774458287427317, -4.6866992525099), Fitness -
1.997744356008841
17
Generation 24: Best individual - (-4.774458287427317, -4.716784426347978), Fitness -
1.9980646589634086
Generation 25: Best individual - (-4.774458287427317, -4.716784426347978), Fitness -
1.9980646589634086
Generation 26: Best individual - (-4.774458287427317, -4.6866992525099), Fitness -
1.997744356008841
Generation 27: Best individual - (-4.774458287427317, -4.6866992525099), Fitness -
1.997744356008841
Generation 28: Best individual - (-4.774458287427317, -4.6866992525099), Fitness -
1.997744356008841
Generation 29: Best individual - (-4.774458287427317, -4.6866992525099), Fitness -
1.997744356008841
Generation 30: Best individual - (-4.774458287427317, -4.748785126215906), Fitness -
1.9974120523172019
Generation 31: Best individual - (-4.774458287427317, -4.776100739600394), Fitness -
1.9960454112384536
Generation 32: Best individual - (-4.774458287427317, -4.776100739600394), Fitness -
1.9960454112384536
Generation 33: Best individual - (-4.774458287427317, -4.776100739600394), Fitness -
1.9960454112384536
Generation 34: Best individual - (-4.774458287427317, -4.748785126215906), Fitness -
1.9974120523172019
Generation 35: Best individual - (-4.774458287427317, -4.748785126215906), Fitness -
1.9974120523172019
Generation 36: Best individual - (-4.774458287427317, -4.748785126215906), Fitness -
1.9974120523172019
Generation 37: Best individual - (-4.774458287427317, -4.6866992525099), Fitness -
1.997744356008841
Generation 38: Best individual - (-4.774458287427317, -4.72866341370584), Fitness -
1.9979418932533646
Generation 39: Best individual - (-4.774458287427317, -4.748785126215906), Fitness -
1.9974120523172019
Generation 40: Best individual - (-4.774458287427317, -4.6866992525099), Fitness -
1.997744356008841
Generation 41: Best individual - (-4.774458287427317, -4.6866992525099), Fitness -
1.997744356008841
Generation 42: Best individual - (-4.774458287427317, -4.6866992525099), Fitness -
1.997744356008841
Generation 43: Best individual - (-4.774458287427317, -4.748785126215906), Fitness -
1.9974120523172019
Generation 44: Best individual - (-4.774458287427317, -4.748785126215906), Fitness -
1.9974120523172019
Generation 45: Best individual - (-4.774458287427317, -4.6866992525099), Fitness -
1.997744356008841
18
Generation 46: Best individual - (-4.774458287427317, -4.748785126215906), Fitness -
1.9974120523172019
Generation 47: Best individual - (-4.774458287427317, -4.6866992525099), Fitness -
1.997744356008841
Generation 48: Best individual - (-4.774458287427317, -4.734085659386703), Fitness -
1.9978389552138645
Generation 49: Best individual - (-4.774458287427317, -4.776100739600394), Fitness -
1.9960454112384536
Generation 50: Best individual - (-4.774458287427317, -4.734085659386703), Fitness -
1.9978389552138645
Best solution found: (-4.774458287427317, -4.734085659386703), Fitness: 1.9978389552138645
RESULT:
Thus the above program implementation of two input sine function using genetic algorithm
executed successfully.
19
Exp.No:07
Date: Implementation of three input nonlinear function
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
import math
20
child1 = (
crossover_point1 * parent1[0] + (1 - crossover_point1) * parent2[0],
crossover_point1 * parent1[1] + (1 - crossover_point1) * parent2[1],
crossover_point1 * parent1[2] + (1 - crossover_point1) * parent2[2]
)
child2 = (
crossover_point2 * parent1[0] + (1 - crossover_point2) * parent2[0],
crossover_point2 * parent1[1] + (1 - crossover_point2) * parent2[1],
crossover_point2 * parent1[2] + (1 - crossover_point2) * parent2[2]
)
if __name__ == "__main__":
generations = 50
pop_size = 100
lower_bound = -1
upper_bound = 1
best_solution = genetic_algorithm(generations, pop_size, lower_bound, upper_bound)
print(f"Best solution found: {best_solution}, Fitness: {fitness_function(*best_solution)}")
21
OUTPUT:
Generation1:Bestindividual-(-0.05856140717606745,0.031920444393859077,
0.1749430018353162),Fitness -23.638248996079486
Generation2:Bestindividual-(-0.0435664961811546,-0.21954873032302427,-
0.16051643562429213),Fitness - 16.78431041370941
Generation3:Bestindividual -(-0.08047256311183462,0.08748607229595336, -
0.033675015554337134),Fitness - 27.03730906535697
Generation4:Bestindividual-(0.09173450837429278,0.2701480951847052,-
0.04923516012359691),Fitness - 16.563306003309293
Generation5:Bestindividual-(0.06931525412773312,0.05650887471327237,-
0.6038978838220976),Fitness -10.126283111803192
Generation6:Bestindividual -(0.09551296321256389,0.3037721680736508,
0.09828297902264888),Fitness - 12.980004103640377
Generation7:Bestindividual-(0.36966788594966404,0.020338697069605532,
0.0003553226927579256),Fitness - 12.951119752237492
Generation8:Bestindividual -(-0.13483009446855374,0.031089470762199117, -
0.5756450454760131),Fitness -7.188833165750407
Generation9:Bestindividual -(-0.063607907585292,-0.04456979821453749,-
0.45149742141484683),Fitness - 9.073275131295658
Generation10:Bestindividual-(0.011176844816005782,0.38683718057120575,-
0.4586668963552707),Fitness--7.626399941503013
Generation11:Bestindividual -(0.42384530453390673,-0.017961106838255136, -
0.4918457018441281),Fitness--9.349262068882442
Generation12:Bestindividual-(0.33991169237820235,0.31387850909754794,-
0.4929268418150241),Fitness--19.707456018578803
Generation13:Bestindividual-(0.4287928945546883,0.5471800246826355,-
0.2740060489612387),Fitness--20.6405201860691
Generation14:Bestindividual-(0.4287928945546883,0.5471800246826355,-
0.2740060489612387),Fitness--20.6405201860691
Generation15:Best individual -(0.4287928945546883,0.5471800246826355,-
0.2740060489612387),Fitness--20.6405201860691
Generation16:Bestindividual-(0.4112385766210301,0.5040715286796309,-
0.3178766342306278),Fitness--23.14240113919352
Generation17:Best individual-(0.4147812368137274,0.5041212646314481,-
0.33531860658801094),Fitness--24.24331785854991
Generation18:Bestindividual-(0.4147812368137274,0.5041212646314481,-
0.33531860658801094),Fitness--24.24331785854991
Generation19:Best individual-(0.4147812368137274,0.5041212646314481,-
0.33531860658801094),Fitness--24.24331785854991
Generation20:Bestindividual-(0.30622472006746704,0.4950670130302236,-
0.44378439110485673),Fitness--23.373347854338835
Generation21:Bestindividual-(0.30622472006746704,0.4950670130302236,-
0.44378439110485673),Fitness--23.373347854338835
Generation22:Bestindividual-(0.3063202575245222,0.4950822379662878,-
0.4437892287140689),Fitness--23.379191958933983
Generation23:Bestindividual-(0.33335312358816604,0.49763301297219154,-
0.43647155864564097),Fitness--24.763115313088132
22
Generation24:Bestindividual-(0.40994188262594977,0.4096825578747779,-
0.42523970750461587),Fitness--26.30751096118025
Generation25:Bestindividual-(0.39756456561304454,0.48504626799164063,-
0.4088104102096408),Fitness--26.9186217943733
Generation26:Bestindividual-(0.38380825053477785,0.5006633169359437,-
0.4288824223540211),Fitness--27.051357458861553
Generation27:Bestindividual-(0.4057387303749639,0.5681504161728289,-
0.4242177696903832),Fitness--26.948969587424035
Generation28:Bestindividual-(0.40511387532462084,0.47856788928174143,-
0.36781261632617945),Fitness--25.457363863631336
Generation29:Bestindividual-(0.40671661145515176,0.4783203340919677,-
0.3735290334571525),Fitness--25.777462228224486
Generation30:Bestindividual-(0.40696169049260167,0.4789885169063051,-
0.3799677735908236),Fitness--26.080160960767703
RESULT:
Thus the above program genetic algorithm for three input non-linear function optimization
executed successfully.
23
24