[go: up one dir, main page]

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

Softcomputing File

The document outlines practical assignments for a Soft Computing lab course for B.Tech Computer Science students. It includes details on various practicals such as creating perceptrons, Adaline networks, autocorrelators, heterocorrelators, fuzzy set operations, and a fuzzy cruise controller using MATLAB. Each practical aims to train neural networks or perform fuzzy operations, accompanied by theoretical explanations and MATLAB code implementations.

Uploaded by

Prabhav Sharma
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)
19 views28 pages

Softcomputing File

The document outlines practical assignments for a Soft Computing lab course for B.Tech Computer Science students. It includes details on various practicals such as creating perceptrons, Adaline networks, autocorrelators, heterocorrelators, fuzzy set operations, and a fuzzy cruise controller using MATLAB. Each practical aims to train neural networks or perform fuzzy operations, accompanied by theoretical explanations and MATLAB code implementations.

Uploaded by

Prabhav Sharma
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

SUBJECT: soft computing

LAB (sc-401p)
FOR
B.TECH(CSE)-7TH SEMESTER
SESSION: 2025-26

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

NAME OF STUDENT: Asmit Kumar Roy

ENROLLMENT NO: 12225502722

SEMESTER: 7th MR GAURAV NAGARKOTI


YEAR & SECTION: 4th ‘B’ ASSISTANT PROFESSOR

NAME: Asmit Kumar Roy ENROLLMENT:12225502722


DATE OF DATE OF TEACHER
S.NO TITLE PRACTICAL Submission SIGNATURE

1.

2.

3.

4.

5.

6.

7.

8.

NAME: Asmit Kumar Roy ENROLLMENT:12225502722


Practical 1
Aim:- Create a perception with appropriate no. of inputs and outputs.
Train it using fixed increment learning algorithm until no change in weight
is required. Output the final weights.
Theory:-
A perceptron is the simplest type of neural network that consists of an
input layer, weights, bias, and an activation function. It classifies input
patterns into linearly separable classes. The Fixed Increment Learning
Algorithm updates the weights by a constant step whenever a
misclassification occurs, and this process continues until the weights
converge. The final stable weights represent the trained perceptron.
Code:-
clear; clc; close();

X = [0 0 1 1; // Input 1
0 1 0 1; // Input 2
1 1 1 1]; // Bias input

T = [0 0 0 1];

W = rand(1, 3) * 0.5;

learning_rate = 0.1;
max_epochs = 100;
disp('Initial Weights (W1, W2, Bias):');
disp(W);

for epoch = 1:max_epochs


error_count = 0;
for i = 1:size(X, 2)
current_X = X(:, i);
current_T = T(i);
net_input = W * current_X;

NAME: Asmit Kumar Roy ENROLLMENT:12225502722


Y = (net_input > 0);

error = current_T - Y;

if error ~= 0
W = W + learning_rate * error * current_X';
error_count = error_count + 1;
end
end

if error_count == 0
disp(['Training converged at epoch: ', string(epoch)]);
break;
end
end
disp('--------------------------');
disp('Final Weights (W1, W2, Bias):');
disp(W);

W1 = W(1);
W2 = W(2);
Bias = W(3);

disp(['Final Weight W1: ', string(W1)]);


disp(['Final Weight W2: ', string(W2)]);
disp(['Final Bias: ', string(Bias)]);

scf();
ax = gca();
ax.title.text = 'Perceptron Decision Boundary for AND Gate';
ax.x_label.text = 'Input 1';
ax.y_label.text = 'Input 2';
ax.data_bounds = [-0.2, -0.2; 1.2, 1.2]; // Set plot limits

class0_indices = find(T == 0);


NAME: Asmit Kumar Roy ENROLLMENT:12225502722
plot(X(1, class0_indices), X(2, class0_indices), 'bo', 'markersize', 8,
'markerfacecolor', 'b');

class1_indices = find(T == 1);


plot(X(1, class1_indices), X(2, class1_indices), 'rs', 'markersize', 8,
'markerfacecolor', 'r');

x1_vals = linspace(-0.2, 1.2, 100);


x2_vals = (-W1 * x1_vals - Bias) / W2;
plot(x1_vals, x2_vals, 'g-', 'linewidth', 2);

legend(['Class 0 (Target=0)', 'Class 1 (Target=1)', 'Decision Boundary'],


'location', 'lowerright');

NAME: Asmit Kumar Roy ENROLLMENT:12225502722


Output:-

NAME: Asmit Kumar Roy ENROLLMENT:12225502722


Practical 2
Aim:- Create a simple Adaline network with appropriate no. of input and
output nodes. Train it using delta learning rule until no change in weights is
required. Output the final weights.
Theory:-
An Adaline (Adaptive Linear Neuron) is a single-layer neural network
where the output is based on a linear combination of inputs and weights.
Unlike the perceptron, it uses the Delta Learning Rule (based on the least
mean square error) to adjust the weights. Training continues until the error
is minimized and the weights converge, resulting in an optimal linear
classifier.
Code:-
clear; clc; close();

X = [ 1 1;
1 -1;
-1 1;
-1 -1];

T = [1; 1; 1; -1];
X_b = [X, ones(size(X, 1), 1)];

W = rand(1, 3) * 0.1;
disp("Initial Weights (w1, w2, bias):");
disp(W);
learning_rate = 0.1;
max_epochs = 50;
tolerance = 0.01;

disp("--- Starting Training ---");


for epoch = 1:max_epochs
sum_squared_error = 0;
NAME: Asmit Kumar Roy ENROLLMENT:12225502722
for i = 1:size(X_b, 1)

y_in = W * X_b(i, :)';

error = T(i) - y_in;

W = W + learning_rate * error * X_b(i, :);


sum_squared_error = sum_squared_error + error^2;
end
disp(['Epoch: ', string(epoch), ', SSE: ', string(sum_squared_error)]);
if sum_squared_error < tolerance
disp("Converged at epoch " + string(epoch));
break;
end
end
disp("--- Training Complete ---");
disp("Final Weights (w1, w2, bias):");
disp(W);

NAME: Asmit Kumar Roy ENROLLMENT:12225502722


Output:-

NAME: Asmit Kumar Roy ENROLLMENT:12225502722


NAME: Asmit Kumar Roy ENROLLMENT:12225502722
Practical 3
Aim:- Train the autocorrelator by given patterns: A1=(-1,1,-1,1) ,
A2=(1,1,1,-1), A3=(-1,-1,-1,1). Test it using patterns: Ax=(-1,1,-1,1),
Ay=(1,1,1,1), Az=(-1,-1,-1,-1).
Theory:-
An autocorrelator neural network is a type of associative memory that
stores patterns and retrieves the same pattern when a noisy or incomplete
version is presented. It is trained using given patterns by constructing a
weight matrix based on the outer product rule. During testing, the stored
patterns are recalled by correlation, ensuring stability and accurate
retrieval of the original input.
Code:-
clear; clc; close();

A1 = [-1, -1, -1, 1, -1];


A2 = [-1, 1, 1, -1, -1];
A3 = [-1, -1, -1, -1, 1];

W = A1' * A1 + A2' * A2 + A3' * A3;

for i = 1:size(W, 1)
W(i, i) = 0;
end

disp("Weight Matrix (W):");


disp(W);

Ax = [-1, -1, 1, 1, 1];


Ay = [1, 1, 1, 1, -1];
Az = [-1, -1, -1, -1, -1];

test_patterns = [Ax; Ay; Az];


pattern_names = ["Ax", "Ay", "Az"];
NAME: Asmit Kumar Roy ENROLLMENT:12225502722
disp("--- Testing Network Recall ---");

function y = activation(x)
y = ones(x);
y(x < 0) = -1;
endfunction

for p = 1:size(test_patterns, 1)
current_pattern = test_patterns(p, :);
disp(" ");
disp(['Testing with pattern: ', pattern_names(p)]);
disp('Input:');
disp(current_pattern);

output_pattern = activation(current_pattern * W);

disp('Output after one step:');


disp(output_pattern);

if isequal(output_pattern, A1) then


disp("Result: Converged to pattern A1");
elseif isequal(output_pattern, A2) then
disp("Result: Converged to pattern A2");
elseif isequal(output_pattern, A3) then
disp("Result: Converged to pattern A3");
else
disp("Result: Did not converge to a stored pattern");
end
end

NAME: Asmit Kumar Roy ENROLLMENT:12225502722


Output:-

NAME: Asmit Kumar Roy ENROLLMENT:12225502722


Practical 4
Aim:- Train the hetrocorrelator using multiple training encoding strategy
for given patterns: A1=(000111001) B1=(010000111), A2=(111001110)
B2=(100000001), A3=(110110101) B3(101001010). Test it using pattern
A2.
Theory:-
A heteroassociative correlator (heterocorrelator) is a type of associative
memory network that stores input–output pattern pairs, where each input
pattern is mapped to a corresponding output pattern. It is trained using a
multiple training encoding strategy, generally based on the outer product
rule. During recall, when a stored input pattern or its noisy version is
applied, the network retrieves the associated output pattern.
Code:-

clear; clc; close();

A1 = [0,0,0,1,1,1,0,0,1];
B1 = [0,1,0,0,0,0,1,1,1];

A2 = [1,1,1,0,0,1,1,1,0];
B2 = [1,0,0,0,0,0,0,0,1];

A3 = [1,1,0,1,1,0,1,0,1];
B3 = [1,0,1,0,0,1,0,1,0];

A1_b = 2*A1 - 1; B1_b = 2*B1 - 1;


A2_b = 2*A2 - 1; B2_b = 2*B2 - 1;
A3_b = 2*A3 - 1; B3_b = 2*B3 - 1;

W = A1_b' * B1_b + A2_b' * B2_b + A3_b' * B3_b;

disp("Weight Matrix (W):");


disp(W);
NAME: Asmit Kumar Roy ENROLLMENT:12225502722
disp("--- Testing Network Recall with A2 ---");

function y = bipolar_activation(x)
y = ones(x);
y(x < 0) = -1;
endfunction

function y = bipolar_to_binary(x)
y = (x + 1) / 2;
endfunction

output_bipolar = bipolar_activation(A2_b * W);

output_binary = bipolar_to_binary(output_bipolar);

disp("Input Pattern (A2 binary):");


disp(A2);
disp("Expected Output (B2 binary):");
disp(B2);
disp("Recalled Output (binary):");
disp(output_binary);

if isequal(output_binary, B2) then


disp("Success: The network correctly recalled pattern B2.");
else
disp("Failure: The network did not recall pattern B2.");
end

NAME: Asmit Kumar Roy ENROLLMENT:12225502722


Output:-

NAME: Asmit Kumar Roy ENROLLMENT:12225502722


Practical 5
Aim:- Implement Union, Intersection, Complement and Difference
operations on fuzzy sets. Also create fuzzy relation by Cartesian product of
any two fuzzy sets and perform maxmin composition on any two fuzzy
relations.
Theory:-
Fuzzy set theory extends classical set theory by allowing elements to have
degrees of membership between 0 and 1. Operations such as Union,
Intersection, Complement, and Difference are defined using membership
functions instead of crisp logic. Fuzzy relations are constructed using the
Cartesian product of fuzzy sets, and their composition (like max–min
composition) is used to model complex relationships between sets.
Code:-
clear; clc; close();

U = [10, 20, 30, 40, 50, 60];

A_membership = [1.0, 0.8, 0.6, 0.4, 0.2, 0.0];


FuzzySet_A = [U; A_membership];

B_membership = [0.0, 0.2, 0.7, 1.0, 0.7, 0.2];


FuzzySet_B = [U; B_membership];

disp("Fuzzy Set A (Young):");


disp(FuzzySet_A);
disp("Fuzzy Set B (Middle-Aged):");
disp(FuzzySet_B);

Union_membership = max(A_membership, B_membership);


disp("Union (A or B):");
disp(Union_membership);

NAME: Asmit Kumar Roy ENROLLMENT:12225502722


Intersection_membership = min(A_membership, B_membership);
disp("Intersection (A and B):");
disp(Intersection_membership);
Complement_A_membership = 1 - A_membership;
disp("Complement of A (not Young):");
disp(Complement_A_membership);
Difference_membership = min(A_membership, 1 - B_membership);
disp("Difference (A - B):");
disp(Difference_membership);
disp("--- Cartesian Product and Composition ---");
X1 = [0.2, 0.5, 0.9]; // Fuzzy Set P on universe {x1, x2, x3}
X2 = [0.4, 0.7]; // Fuzzy Set Q on universe {y1, y2}
Relation_R = zeros(length(X1), length(X2));
for i = 1:length(X1)
for j = 1:length(X2)
Relation_R(i, j) = min(X1(i), X2(j));
end
end
disp("Fuzzy Relation R (Cartesian Product of P and Q):");
disp(Relation_R);

Relation_S = [0.6, 0.1;


0.3, 0.8];
Composition_Result = zeros(size(Relation_R, 1), size(Relation_S, 2));
for i = 1:size(Relation_R, 1)
for j = 1:size(Relation_S, 2)

min_values = min(Relation_R(i, :), Relation_S(:, j)');


Composition_Result(i, j) = max(min_values);
end
end
disp("Max-Min Composition of R and S:");
disp(Composition_Result);

NAME: Asmit Kumar Roy ENROLLMENT:12225502722


Output:-

NAME: Asmit Kumar Roy ENROLLMENT:12225502722


Practical 6
Aim:- Solve Greg Viot’s fuzzy cruise controller using MATLAB Fuzzy
logic toolbox.
Theory:-
Greg Viot’s fuzzy cruise controller is a classic application of fuzzy logic in
automotive systems, designed to maintain a vehicle’s speed under varying
road conditions. It uses fuzzy rules and membership functions to model
human-like decision making for throttle adjustments. By implementing it in
the MATLAB Fuzzy Logic Toolbox, the controller can be simulated and
analyzed effectively for stable speed regulation.
Code:-
clear; clc; close all;
fis = mamfis('Name', 'cruiseController');

fis = addInput(fis, [-10 10], 'Name', 'SpeedError');


fis = addMF(fis, 'SpeedError', 'trimf', [-10 -10 0], 'Name', 'Negative');
fis = addMF(fis, 'SpeedError', 'trimf', [-2 0 2], 'Name', 'Zero');
fis = addMF(fis, 'SpeedError', 'trimf', [0 10 10], 'Name', 'Positive');

fis = addInput(fis, [-5 5], 'Name', 'Acceleration');


fis = addMF(fis, 'Acceleration', 'trimf', [-5 -5 0], 'Name', 'Slowing');
fis = addMF(fis, 'Acceleration', 'trimf', [-1 0 1], 'Name', 'Steady');
fis = addMF(fis, 'Acceleration', 'trimf', [0 5 5], 'Name', 'SpeedingUp');

fis = addOutput(fis, [-8 8], 'Name', 'ThrottleChange');


fis = addMF(fis, 'ThrottleChange', 'trimf', [-8 -8 0], 'Name', 'Decrease');
fis = addMF(fis, 'ThrottleChange', 'trimf', [-2 0 2], 'Name', 'None');
fis = addMF(fis, 'ThrottleChange', 'trimf', [0 8 8], 'Name', 'Increase');
ruleList = [3 0 3 1 1;
1 0 1 1 1;
2 2 2 1 1;
1 3 1 1 1];

NAME: Asmit Kumar Roy ENROLLMENT:12225502722


fis = addRule(fis, ruleList);
disp('Cruise Controller FIS created.');
fprintf('\n--- Evaluating Controller ---\n');
output_throttle1 = evalfis(fis, [5 0]);
fprintf('Case 1 (5 kph too slow): Throttle Change = %.2f%%\n',
output_throttle1);
output_throttle2 = evalfis(fis, [0 -3]);
fprintf('Case 2 (Slowing down at target speed): Throttle Change =
%.2f%%\n', output_throttle2);

output_throttle3 = evalfis(fis, [-3 2]);


fprintf('Case 3 (Too fast and accelerating): Throttle Change = %.2f%%\n',
output_throttle3);
figure;
subplot(2,2,1);
plotmf(fis, 'input', 1);
title('Speed Error Membership Functions');

subplot(2,2,2);
plotmf(fis, 'input', 2);
title('Acceleration Membership Functions');

subplot(2,2,3);
plotmf(fis, 'output', 1);
title('Throttle Change Membership Functions');

NAME: Asmit Kumar Roy ENROLLMENT:12225502722


Output:-

NAME: Asmit Kumar Roy ENROLLMENT:12225502722


Practical 7
Aim:- Solve Air Conditioner Controller using MATLAB Fuzzy logic
toolbox.
Theory:-
A fuzzy logic–based air conditioner controller regulates room temperature
by mimicking human decision-making using linguistic rules. Inputs such as
temperature error and rate of change are mapped into fuzzy sets, and
control actions are derived through fuzzy inference. Using the MATLAB
Fuzzy Logic Toolbox, the controller is designed and simulated to achieve
smooth and efficient temperature control.
Code:-
clear; clc; close all;

fis = mamfis('Name', 'acController');

fis = addInput(fis, [-5 5], 'Name', 'TempError');


fis = addMF(fis, 'TempError', 'trimf', [-5 -5 0], 'Name', 'Cold'); % Room is
colder than setpoint
fis = addMF(fis, 'TempError', 'trimf', [-1 0 1], 'Name', 'Good'); % Room is at
setpoint
fis = addMF(fis, 'TempError', 'trimf', [0 5 5], 'Name', 'Hot'); % Room is
hotter than setpoint

fis = addInput(fis, [0 100], 'Name', 'Humidity');


fis = addMF(fis, 'Humidity', 'trimf', [0 0 50], 'Name', 'Low');
fis = addMF(fis, 'Humidity', 'trimf', [50 100 100], 'Name', 'High');

fis = addOutput(fis, [0 100], 'Name', 'CompressorSpeed');


fis = addMF(fis, 'CompressorSpeed', 'trimf', [0 0 10], 'Name', 'Off');
fis = addMF(fis, 'CompressorSpeed', 'trimf', [10 30 50], 'Name', 'Slow');
fis = addMF(fis, 'CompressorSpeed', 'trimf', [40 60 80], 'Name', 'Medium');
fis = addMF(fis, 'CompressorSpeed', 'trimf', [70 100 100], 'Name', 'Fast');

NAME: Asmit Kumar Roy ENROLLMENT:12225502722


ruleList = [1 0 1 1 1;
2 0 2 1 1;
3 1 3 1 1;
3 2 4 1 1];

fis = addRule(fis, ruleList);

disp('AC Controller FIS created.');

fprintf('\n--- Evaluating Controller ---\n');


output_speed1 = evalfis(fis, [3 30]);
fprintf('Case 1 (Hot, Low Humidity): Compressor Speed = %.2f%%\n',
output_speed1);

output_speed2 = evalfis(fis, [3 80]);


fprintf('Case 2 (Hot, High Humidity): Compressor Speed = %.2f%%\n',
output_speed2);

output_speed3 = evalfis(fis, [-2 50]);


fprintf('Case 3 (Too Cold): Compressor Speed = %.2f%%\n',
output_speed3);

figure;
subplot(2,2,1);
plotmf(fis, 'input', 1);
title('Temperature Error Membership Functions');
subplot(2,2,2);
plotmf(fis, 'input', 2);
title('Humidity Membership Functions');
subplot(2,2,3);
plotmf(fis, 'output', 1);
title('Compressor Speed Membership Functions');

NAME: Asmit Kumar Roy ENROLLMENT:12225502722


Output:-

NAME: Asmit Kumar Roy ENROLLMENT:12225502722


Practical 8
Aim:- Implement TSP using GA.
Theory:-
The Travelling Salesman Problem (TSP) is a classical optimization
problem that aims to find the shortest possible route visiting each city
exactly once and returning to the starting point. Genetic Algorithms (GA)
solve TSP by simulating natural evolution using operations like selection,
crossover, and mutation. This approach provides near-optimal solutions
efficiently for large and complex TSP instances.
Code:-
clear; clc; close all;

num_cities = 20;

rng(1);
cities = rand(num_cities, 2) * 100;

dist_matrix = pdist2(cities, cities);

fitness_fcn = @(tour) total_distance(tour, dist_matrix);

options = optimoptions('ga', 'Display', 'iter', 'MaxGenerations', 200,


'PopulationSize', 100);

fprintf('Starting Genetic Algorithm for TSP...\n');


intcon = 1:num_cities;
[best_tour, min_dist] = ga(fitness_fcn, num_cities, [], [], [], [], 1, num_cities,
[], intcon, options);

fprintf('\n--- GA Finished ---\n');


fprintf('Best tour found:\n');
disp(best_tour);
fprintf('Minimum tour distance: %.2f\n', min_dist);
NAME: Asmit Kumar Roy ENROLLMENT:12225502722
figure;
plot(cities(:,1), cities(:,2), 'bo', 'MarkerSize', 8, 'MarkerFaceColor', 'b');
hold on;
tour_coords = cities(best_tour, :);
tour_coords(end+1, :) = tour_coords(1, :);
plot(tour_coords(:,1), tour_coords(:,2), 'r-', 'LineWidth', 1.5);
title(['Best Tour Found (Distance: ' num2str(min_dist, '%.2f') ')']);
xlabel('X Coordinate');
ylabel('Y Coordinate');
grid on;
hold off;

function total_dist = total_distance(tour, dist_matrix)

total_dist = 0;
for i = 1:(length(tour) - 1)
total_dist = total_dist + dist_matrix(tour(i), tour(i+1));
end
total_dist = total_dist + dist_matrix(tour(end), tour(1));
end

NAME: Asmit Kumar Roy ENROLLMENT:12225502722


Output:-

NAME: Asmit Kumar Roy ENROLLMENT:12225502722

You might also like