0% found this document useful (0 votes)
9 views

SC - LAB

The document outlines the practical exercises for the Soft Computing course at Einstein College of Engineering for the academic year 2024-2025. It includes various programming tasks such as implementing fuzzy control systems, discrete perceptrons, XOR with backpropagation, self-organizing maps, and genetic algorithms, along with their respective aims, programs, outputs, and results. Each exercise demonstrates successful execution and verification of the implemented Python programs.

Uploaded by

pathisiva2004
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)
9 views

SC - LAB

The document outlines the practical exercises for the Soft Computing course at Einstein College of Engineering for the academic year 2024-2025. It includes various programming tasks such as implementing fuzzy control systems, discrete perceptrons, XOR with backpropagation, self-organizing maps, and genetic algorithms, along with their respective aims, programs, outputs, and results. Each exercise demonstrates successful execution and verification of the implemented Python programs.

Uploaded by

pathisiva2004
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/ 22

EINSTEIN COLLEGE OF ENGINEERING

SIR C.V.RAMAN NAGAR , TIRUNELVELI – 627012

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LAB MANUVAL

ACADEMIC YEAR : 2024 – 2025 (REGULATION – 2021)

STUDENT NAME :

REGISTER NUMBER :

PROGRAMME : UG

YEAR / SEMESTER : III / VI

COURSE CODE : CCS364

COURSE NAME : SOFT COMPUTING


CCS364 – SOFT COMPUTING

PRACTICAL EXERCISES:

1. Implementation of fuzzy control/inference system.

2. Programming exercise on classification with a discrete perceptron.

3. Implementation of XOR with backpropagation algorithm.

4. Implementation of self-organizing maps for a specific application.

5. Programming exercises on maximizing a function using Genetic

algorithm.

6. Implementation of two-input sine function.

7. Implementation of three-input non-linear function.


1. Implementation of fuzzy control/inference system

AIM :

To write a python program to implementation of fuzzy


control/inference system.

PROGRAM :

import matplotlib.pyplot as plt


import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
temperature = ctrl.Antecedent(np.arange(0, 101, 1), 'temperature')
fan_speed = ctrl.Consequent(np.arange(0, 101, 1), 'fan_speed')
temperature['low'] = fuzz.trimf(temperature.universe, [0, 0, 50])
temperature['medium'] = fuzz.trimf(temperature.universe, [0, 50,
100])
temperature['high'] = fuzz.trimf(temperature.universe, [50, 100, 100])
fan_speed['low'] = fuzz.trimf(fan_speed.universe, [0, 0, 50])
fan_speed['medium'] = fuzz.trimf(fan_speed.universe, [0, 50, 100])
fan_speed['high'] = fuzz.trimf(fan_speed.universe, [50, 100, 100])
rule1 = ctrl.Rule(temperature['low'], fan_speed['low'])
rule2 = ctrl.Rule(temperature['medium'], fan_speed['medium'])
rule3 = ctrl.Rule(temperature['high'], fan_speed['high'])
fan_ctrl = ctrl.ControlSystem([rule1, rule2, rule3])
fan_speed_ctrl = ctrl.ControlSystemSimulation(fan_ctrl)
temperature_value = 75
fan_speed_ctrl.input['temperature'] = temperature_value
fan_speed_ctrl.compute()
print("Fan Speed:", fan_speed_ctrl.output['fan_speed'])
temperature.view()
fan_speed.view()
fan_speed.view(sim=fan_speed_ctrl)
plt.show()
OUTPUT :

Fan Speed: 55.95238095238095


RESULT :

Thus the python program to implementation of fuzzy


control/inference system was executed successfully and the output is
verified.
2. Programming exercise on classification with a discrete
perceptron

AIM :

To write a python program to programming exercise on


classification with a discrete perceptron.

PROGRAM :

import numpy as np
class DiscretePerceptron:
def __init__(self, input_size):
self.weights = np.zeros(input_size)
self.bias = 0
def predict(self, inputs):
activation = np.dot(self.weights, inputs) + self.bias
return 1 if activation > 0 else 0
def train(self, inputs, target, learning_rate=0.1, epochs=100):
for _ in range(epochs):
for x, y in zip(inputs, target):
prediction = self.predict(x)
error = y - prediction
self.weights += learning_rate * error * x
self.bias += learning_rate * error
print("Training completed!")
print("Final Weights:", self.weights)
print("Final Bias:", self.bias)
def main():
class_0 = np.array([[2, 3], [3, 2], [1, 1]])
class_1 = np.array([[5, 7], [6, 8], [7, 6]])
inputs = np.vstack((class_0, class_1))
targets = np.array([0, 0, 0, 1, 1, 1])
perceptron = DiscretePerceptron(input_size=2)
perceptron.train(inputs, targets)
test_data = np.array([[4, 5], [3, 4], [6, 7]])
for data in test_data:
prediction = perceptron.predict(data)
if prediction == 0:
print(f"Data {data} belongs to class 0")
else:
print(f"Data {data} belongs to class 1")
if __name__ == "__main__":
main()

OUTPUT :

Training completed!
Final Weights: [-0.1 0.5]
Final Bias: -1.3
Data [4 5] belongs to class 1
Data [3 4] belongs to class 1
Data [6 7] belongs to class 1

RESULT :

Thus the python program to programming exercise on


classification with a discrete perceptron was executed successfully
and the output is verified.
3. Implementation of XOR with backpropagation algorithm

AIM :

To write a python program to implementation of XOR with


backpropagation algorithm.

PROGRAM :

import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1 - x)
input_data = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
target_data = np.array([[0], [1], [1], [0]])
input_size = 2
hidden_size = 2
output_size = 1
learning_rate = 0.1
epochs = 10000
hidden_weights = np.random.uniform(size=(input_size, hidden_size))
output_weights = np.random.uniform(size=(hidden_size,
output_size))
for _ in range(epochs):
hidden_layer_activation = np.dot(input_data, hidden_weights)
hidden_layer_output = sigmoid(hidden_layer_activation)
output_layer_activation = np.dot(hidden_layer_output,
output_weights)
predicted_output = sigmoid(output_layer_activation)
error = target_data - predicted_output
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)
output_weights += hidden_layer_output.T.dot(output_delta) *
learning_rate
hidden_weights += input_data.T.dot(hidden_layer_delta) *
learning_rate
test_data = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
print("Testing Results:")
for data in test_data:
hidden_layer_activation = np.dot(data, hidden_weights)
hidden_layer_output = sigmoid(hidden_layer_activation)
output_layer_activation = np.dot(hidden_layer_output,
output_weights)
predicted_output = sigmoid(output_layer_activation)
print(f"Input: {data} Predicted Output: {predicted_output[0]}")

OUTPUT :

Testing Results:
Input: [0 0] Predicted Output: 0.1928003136839193
Input: [0 1] Predicted Output: 0.7456280321708408
Input: [1 0] Predicted Output: 0.7456333725827692
Input: [1 1] Predicted Output: 0.3316986355682776

RESULT :

Thus the python program to implementation of XOR with


backpropagation algorithm was executed successfully and the output
is verified.
4. Implementation of self-organizing maps for a specific
application

AIM :

To write a python program to implementation of self-organizing


maps for a specific application.

PROGRAM :

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(42)
data = np.random.rand(100, 2)
grid_size = (10, 10)
input_dim = 2
learning_rate = 0.2
num_epochs = 1000
weight_matrix = np.random.rand(grid_size[0], grid_size[1],
input_dim)
for epoch in range(num_epochs):
for input_vector in data:
distances = np.linalg.norm(weight_matrix - input_vector, axis=-
1)
bmu_coords = np.unravel_index(np.argmin(distances),
distances.shape)
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))
weight_matrix[i, j] += influence * learning_rate *
(input_vector - weight_matrix[i, j])
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)
plt.figure(figsize=(8, 8))
plt.pcolormesh(cluster_map, cmap='viridis', edgecolors='k')
plt.colorbar(label='Cluster')
plt.scatter(data[:, 0] * grid_size[0], data[:, 1] * grid_size[1],
color='red', label='Data points', alpha=0.7)
plt.legend()
plt.title('Self-Organizing Map Clustering')
plt.xlabel('Grid X')
plt.ylabel('Grid Y')
plt.show()
OUTPUT :

RESULT :

Thus the python program to implementation of self-organizing


maps for a specific application was executed successfully and the
output is verified.
5. Programming exercises on maximizing a function using
Genetic algorithm

AIM :

To write a python program to programming exercises on


maximizing a function using Genetic algorithm.

PROGRAM :

import random
def fitness_function(x):
return -x**2 + 6*x + 9
def initialize_population(pop_size, lower_bound, upper_bound):
return [random.uniform(lower_bound, upper_bound) for _ in
range(pop_size)]
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
def crossover(parent1, parent2, crossover_prob=0.7):
if random.random() < crossover_prob:
crossover_point = random.randint(0, 1)
child1 = (parent1 + parent2) / 2
child2 = (parent1 + parent2) / 2
return child1, child2
else:
return parent1, parent2
def mutate(individual, mutation_prob=0.01):
if random.random() < mutation_prob:
individual += random.uniform(-1,1)
return individual
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)
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 :

Generation 1: Best individual - 2.2937827079868205, Fitness -


17.50125713646157
Generation 2: Best individual - 9.10610042041553, Fitness - -
19.2844623441987
Generation 3: Best individual - -5.410143313474801, Fitness - -
52.730510553184914
Generation 4: Best individual - -6.896718279457372, Fitness - -
79.94503270294568
Generation 5: Best individual - -7.746684835251414, Fitness - -
97.49123494822271
Generation 6: Best individual - -7.746684835251414, Fitness - -
97.49123494822271
Generation 7: Best individual - -8.058833417552439, Fitness - -
104.29779655717456
Generation 8: Best individual - -8.150505364838667, Fitness - -
106.33376989129589
Generation 9: Best individual - -8.18524194018208, Fitness - -
107.10963726040816
Generation 10: Best individual - -8.256111908146462, Fitness - -
108.70005528871658
Generation 11: Best individual - -8.256111908146462, Fitness - -
108.70005528871658
Generation 12: Best individual - -8.256111908146462, Fitness - -
108.70005528871658
Generation 13: Best individual - -8.30557309882241, Fitness - -
109.81598309281696
Generation 14: Best individual - -8.326556480595237, Fitness - -
110.29088170811396
Generation 15: Best individual - -7.8904915235174595, Fitness - -
100.60280562380564
Generation 16: Best individual - -8.080503266184309, Fitness - -
104.77755263192113
Generation 17: Best individual - -8.250191936586022, Fitness - -
108.56681861002515
Generation 18: Best individual - -8.250191936586022, Fitness - -
108.56681861002515
Generation 19: Best individual - -7.484183496440571, Fitness - -
91.91810358703684
Generation 20: Best individual - -7.948517957481421, Fitness - -
101.87004546529315
Generation 21: Best individual - -7.948517957481421, Fitness - -
101.87004546529315
Generation 22: Best individual - -7.948517957481421, Fitness - -
101.87004546529315
Generation 23: Best individual - -7.593540796903103, Fitness - -
94.22310661565042
Generation 24: Best individual - -8.155949190937516, Fitness - -
106.45520235077942
Generation 25: Best individual - -8.155949190937516, Fitness - -
106.45520235077942
Generation 26: Best individual - -8.30540840437621, Fitness - -
109.81225918974026
Generation 27: Best individual - -8.30540840437621, Fitness - -
109.81225918974026
Generation 28: Best individual - -7.4903368613674735, Fitness - -
92.04716746496517
Generation 29: Best individual - -8.377717163032738, Fitness - -
111.45244784196973
Generation 30: Best individual - -8.16782992041845, Fitness - -
106.72042513139357
Generation 31: Best individual - -7.565224957250624, Fitness - -
93.62397839731145
Generation 32: Best individual - -7.995649123452813, Fitness - -
102.9042996460886
Generation 33: Best individual - -7.995649123452813, Fitness - -
102.9042996460886
Generation 34: Best individual - -8.172177759026827, Fitness - -
106.81755587929368
Generation 35: Best individual - -7.763872972179094, Fitness - -
97.8609613612076
Generation 36: Best individual - -8.052138031809593, Fitness - -
104.14975507417202
Generation 37: Best individual - -7.5039509049116155, Fitness - -
92.33298461279355
Generation 38: Best individual - -7.916596424396227, Fitness - -
101.17207749314048
Generation 39: Best individual - -7.916596424396227, Fitness - -
101.17207749314048
Generation 40: Best individual - -7.6518115023839055, Fitness - -
95.46108828231807
Generation 41: Best individual - -7.6518115023839055, Fitness - -
95.46108828231807
Generation 42: Best individual - -7.6518115023839055, Fitness - -
95.46108828231807
Generation 43: Best individual - -8.16230487467131, Fitness - -
106.5970501151109
Generation 44: Best individual - -8.167406403525582, Fitness - -
106.71096578150419
Generation 45: Best individual - -8.014048029651287, Fitness - -
103.3092539994654
Generation 46: Best individual - -8.239686971901717, Fitness - -
108.33056322633719
Generation 47: Best individual - -8.29801638463299, Fitness - -
109.64517422743552
Generation 48: Best individual - -8.337203334330452, Fitness - -
110.53217944395351
Generation 49: Best individual - -8.337203334330452, Fitness - -
110.53217944395351
Generation 50: Best individual - -8.375425472948024, Fitness - -
111.40030469059477
Best solution found: -8.375425472948024, Fitness: -
111.40030469059477

RESULT :

Thus the python program to programming exercises on


maximizing a function using Genetic algorithm was executed
successfully and the output is verified.
6. Implementation of two-input sine function

AIM :

To write a python program to implementation of two-input sine


function.

PROGRAM :

import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
x, y, z = ctrl.Antecedent(np.arange(-10, 10, 0.1), 'x'),
ctrl.Antecedent(np.arange(-10, 10, 0.1), 'y'),
ctrl.Consequent(np.arange(-1, 1, 0.01), 'z')
x['low'], x['high'] = fuzz.trapmf(x.universe, [-10, -5, -2.5, 0]),
fuzz.trapmf(x.universe, [0, 2.5, 5, 10])
y['low'], y['high'] = fuzz.trapmf(y.universe, [-10, -5, -2.5, 0]),
fuzz.trapmf(y.universe, [0, 2.5, 5, 10])
z['neg'], z['pos'] = fuzz.trapmf(z.universe, [-1, -0.75, -0.5, -0.25]),
fuzz.trapmf(z.universe, [0.25, 0.5, 0.75, 1])
system = ctrl.ControlSystem([ctrl.Rule(x['low'] & y['low'], z['neg']),
ctrl.Rule(x['high'] & y['high'], z['pos'])])
sim = ctrl.ControlSystemSimulation(system)
sim.input['x'], sim.input['y'] = 3, 4
sim.compute()
print(f'Fuzzy output: {sim.output["z"]}')
print(f'Actual output: {np.sin(np.sqrt(3**2 + 4**2))}')
OUTPUT :

Fuzzy output: 0.6248526077097506


Actual output: -0.9589242746631385

RESULT :

Thus the python program to implementation of two-input sine


function was executed successfully and the output is verified.
7. Implementation of three-input non-linear function

AIM :

To write a python program to implementation of three-input


non-linear function.

PROGRAM :

import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
x, y, z, output = ctrl.Antecedent(np.arange(-10, 10, 0.1), 'x'),
ctrl.Antecedent(np.arange(-10, 10, 0.1), 'y'),
ctrl.Antecedent(np.arange(-10, 10, 0.1), 'z'),
ctrl.Consequent(np.arange(-100, 100, 0.1), 'output')
x['low'], x['high'] = fuzz.trapmf(x.universe, [-10, -5, -2.5, 0]),
fuzz.trapmf(x.universe, [0, 2.5, 5, 10])
y['low'], y['high'] = fuzz.trapmf(y.universe, [-10, -5, -2.5, 0]),
fuzz.trapmf(y.universe, [0, 2.5, 5, 10])
z['low'], z['high'] = fuzz.trapmf(z.universe, [-10, -5, -2.5, 0]),
fuzz.trapmf(z.universe, [0, 2.5, 5, 10])
output['low'], output['high'] = fuzz.trapmf(output.universe, [-100, -50,
-25, 0]), fuzz.trapmf(output.universe, [0, 25, 50, 100])
rule1, rule2 = ctrl.Rule(x['low'] & y['low'] & z['low'], output['low']),
ctrl.Rule(x['high'] & y['high'] & z['high'], output['high'])
system = ctrl.ControlSystem([rule1, rule2])
sim = ctrl.ControlSystemSimulation(system)
x_val, y_val, z_val = 3, 4, 2
sim.input['x'], sim.input['y'], sim.input['z'] = x_val, y_val, z_val
sim.compute()
fuzzy_output = sim.output["output"]
print(f'Fuzzy output: {fuzzy_output}')
actual_output = x_val**2 + 2*y_val**2 - 3*z_val**2 +
2*x_val*y_val - z_val
print(f'Actual output: {actual_output}')
OUTPUT :

Fuzzy output: 45.71418889438485


Actual output: 51

RESULT :

Thus the python program to implementation of three-input non-


linear function was executed successfully and the output is verified.

You might also like