0% found this document useful (0 votes)
4 views30 pages

Soft Computing File

The document provides an introduction to Soft and Hard Computing, detailing their characteristics, techniques, and applications. Soft Computing deals with uncertainty and approximation, utilizing methods like Fuzzy Logic and Neural Networks, while Hard Computing relies on precise mathematical models and deterministic algorithms. Additionally, it includes practical experiments on fuzzy operations, relations, and controllers, demonstrating their implementation and real-world applications.

Uploaded by

Harsh Deshpande
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)
4 views30 pages

Soft Computing File

The document provides an introduction to Soft and Hard Computing, detailing their characteristics, techniques, and applications. Soft Computing deals with uncertainty and approximation, utilizing methods like Fuzzy Logic and Neural Networks, while Hard Computing relies on precise mathematical models and deterministic algorithms. Additionally, it includes practical experiments on fuzzy operations, relations, and controllers, demonstrating their implementation and real-world applications.

Uploaded by

Harsh Deshpande
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

Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore

Shri Vaishnav Institute of Information Technology

EXPERIMENT NO:-1

AIM: Introduction to Soft Computing & Hard Computing.


Computing:
Computing refers to the process of using computer systems and algorithms to perform calculations,
process data, and solve problems automatically. It involves hardware (physical components) and
software (programs and algorithms) working together to perform logical or mathematical tasks.
Key Points:

• Involves data processing, logic, and automation


• Uses both hardware (physical devices) and software (programs) Core to fields like AI,
IT, data science, cybersecurity. Types: Hard Computing, Soft Computing, etc.

Soft Computing:
Soft Computing is a branch of computing that deals with approximate models, uncertainty, and
imprecision — just like the human brain does when making decisions. It provides flexible and
intelligent solutions for complex, uncertain, or imprecise real-world problems. Soft computing is
not about finding the perfect solution, but the best possible solution within acceptable limits.
Characteristics of Soft Computing:

• Deals with uncertainty and approximation: Tolerates imprecision in data.


• Mimics human reasoning and learning.
• Low computational cost for certain types of problems.
• Adaptive and robust: can handle changing data or environments.
• Aims for an approximate solution rather than an exact one.

NAME:-Akash 1 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

Main Techniques of Soft Computing:

• Fuzzy Logic (FL): Handles reasoning that is approximate rather than exact. Example:
“The room is warm” instead of saying “temperature = 30°C.”
• Neural Networks (ANN): Learns patterns from data and makes predictions. Example:
Face or voice recognition.
• Genetic Algorithms (GA): Optimization technique inspired by natural evolution.
Example: Route optimization in Google Maps.
• Probabilistic Reasoning: Deals with uncertainty using probabilities.
• Rough Sets: Deals with vagueness by approximating data sets.
Need For Soft Computing:

• Many analytical models are valid for ideal cases. Real-world problems exist in a nonideal
environment.
• Soft computing provides insights into real-world problems and is just not limited to
theory.
• Hard computing is best suited for solving mathematical problems which give some
precise answers.
• Some important fields like Biology, Medicine and humanities, etc are still intractable
using Convention mathematical and Analytical models.
• It is possible to map the human mind with the help of Soft computing but it is not
possible with Convention mathematical and Analytical models.

NAME:-Akash 2 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

Hard Computing:
Hard Computing refers to traditional (conventional) computing methods that rely on precise
mathematical models, exact logic, and deterministic algorithms to get accurate and exact results.
It follows the principles of binary logic — meaning True (1) or False (0) — with no room for
uncertainty or approximation.
Characteristics of Hard Computing:

• Requires exact input data: No tolerance for uncertainty or inaccuracy.


• Based on mathematical models and algorithms
• Uses methods like numerical analysis, logic, and arithmetic.
• Deterministic nature: Same input always produces the same output.
• High computational cost for complex problems.
• Rigid structure — not adaptable to changing environments.
Main Techniques of Hard Computing:

• Deterministic Algorithms: Follow a fixed sequence of steps to produce exact and


predictable results.
Example: Sorting algorithms like Merge Sort or Binary Search for precise outputs.
• Numerical Methods: Use mathematical equations and formulas to find exact solutions to
problems.
Example: Newton-Raphson method for solving equations or Gaussian elimination for
linear systems.
• Boolean Logic (Symbolic Logic): Based on binary values (0 and 1) and logical
operations such as AND, OR, NOT.
Example: Used in digital circuit design and computer processors.
• Statistical Methods: Analyze accurate numerical data using mathematical and statistical
formulas.
Example: Regression analysis or Hypothesis testing for exact data interpretation.
• Optimization Techniques: Find the most optimal solution from a set of possibilities using
mathematical modeling.
Example: Linear Programming and Dynamic Programming.
• Control Theory (Classical Control): Used to design systems that maintain desired outputs
using mathematical model.
Example: PID controllers in industrial [Link]-Based Systems: Make decisions based on
predefined logical “if–then” rules with exact conditions.

NAME:-Akash 3 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

EXPERIMENT NO:-2

AIM: Implementation of Fuzzy Operations.


OBJECTIVE: To implement basic fuzzy set operations such as union, intersection, and
complement.
OUTCOME: After completing this practical, students will understand how fuzzy sets handle
uncertainty and how basic operations are applied on fuzzy sets.
THEORY: In classical set theory, an element either belongs to a set (membership = 1) or it doesn’t
(membership = 0).In fuzzy set theory, an element can belong to a set with a degree of membership
between 0 and 1. Fuzzy set theory extends classical set theory by allowing partial membership
values in the range [0,1].
To work with these fuzzy sets, we define operations similar to classical sets but generalized.
1. Union (OR Operation):
Combines two fuzzy sets.
For each element x:
μA B(x)=max(μA(x), μB(x))
Intuition: take the highest membership from both sets.
1. Intersection (AND Operation):

• Finds the commonality between two fuzzy sets.

• For each element x: μA∩B(x)=min(μA(x), μB(x))


Intuition: take the lowest membership from both sets.
1. Complement (NOT Operation)

Represents everything not in the fuzzy set.


For each element x: μAˉ(x)=1−μA(x)
Intuition: if something is 0.7 in A, then it is 0.3 outside A.

NAME:-Akash 4 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

1. Difference Defined as:


μA−B(x)=min(μA
(x),1−μB(x))

import [Link].*;

public class FuzzySetOperations {

public static void main(String[] args) {

// Fuzzy sets A and B


Map<Integer, Double> A = new HashMap<>();
[Link](1, 0.2);
A. put(2, 0.7);
A. put(3, 0.9);

Map<Integer, Double> B = new HashMap<>();


[Link](1, 0.6);
B. put(2, 0.4);
B. put(3, 0.8);

// Union: μA B(x) = max(μA(x), μB(x))


Map<Integer, Double> union = new HashMap<>();
for (int x : [Link]()) { [Link](x,
[Link]([Link](x), [Link](x)));
}

// Intersection: μA∩B(x) = min(μA(x), μB(x))


Map<Integer, Double> intersection = new HashMap<>();
for (int x : [Link]()) { [Link](x,
[Link]([Link](x), [Link](x)));
}

// Complement of A: μA'(x) = 1 − μA(x)


Map<Integer, Double> complementA = new HashMap<>();
for (int x : [Link]()) {
[Link](x, 1 - [Link](x));
}

NAME:-Akash 5 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

// Difference: μA−B(x) = min(μA(x), 1 − μB(x))


Map<Integer, Double> difference = new HashMap<>();
for (int x : [Link]()) { [Link](x,
[Link]([Link](x), 1 - [Link](x)));
}

// Print results
[Link]("Fuzzy Set A: " + A);
[Link]("Fuzzy Set B: " + B);
[Link]("Union (A B): " + union);
[Link]("Intersection (A ∩ B): " + intersection);
[Link]("Complement of A: " + complementA);
[Link]("Difference (A − B): " + difference);
}
}
OUTPUT:

CONCLUSION:
The experiment successfully demonstrated basic fuzzy set operations such as union, intersection,
complement, and difference. Unlike classical set operations, fuzzy operations handle partial
membership values in the range [0,1], which makes them suitable for modeling uncertainty and
vagueness in real-world problems.

NAME:-Akash 6 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

EXPERIMENT NO:-3

AIM: Implementation of Fuzzy Relations (Max–Min Composition).


OBJECTIVE: To study fuzzy relations and implement the max–min composition between two
fuzzy relations.
OUTCOME: Students will be able to compute fuzzy relational compositions, which are useful in
fuzzy inference and decision-making systems.
THEORY: A fuzzy relation is an extension of a crisp relation where membership values can range
between [0,1]. If R (X→Y) and S (Y→Z) are two fuzzy relations, then the max–min composition
(R ○ S) is defined as: μR○S(x,z)=ymaxmin(μR(x,y),μS(y,z)) This
composition is commonly used in fuzzy inference systems.
CODE:
public class FuzzyMaxMinComposition {

public static void main(String[] args) {


// Relation R: X → Y
double[][] R = {
{0.2, 0.7},
{0.5, 0.9}
};
// Relation S: Y → Z
double[][] S = {
{0.6, 0.8},
{0.3, 0.4}
};
int rows = [Link]; int cols = S[0].length;
int common = R[0].length; // Max–min
composition matrix double[][] composition = new
double[rows][cols];
// Compute max–min composition for (int i =
0; i < rows; i++) { for (int j = 0; j < cols; j++) {
double maxVal = 0.0; for (int k = 0; k <
common; k++) { double minVal =

NAME:-Akash 7 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

[Link](R[i][k], S[k][j]); if (minVal >


maxVal) maxVal = minVal;
}
composition[i][j] = maxVal;
}
}
// Print results
[Link]("Relation R:");
printMatrix(R);
[Link]("\nRelation S:");
printMatrix(S);
[Link]("\nMax–Min Composition (R ○ S):");
printMatrix(composition);
}
// Utility method to print 2D array public static
void printMatrix(double[][] matrix) { for
(double[] row : matrix) { for (double val :
row) {
[Link]("%.2f ", val);
}
[Link]();
}
}
}
OUTPUT:

CONCLUSION:
Max–min composition of fuzzy relations was implemented, demonstrating how fuzzy relations
combine information for inference and decision-making.

NAME:-Akash 8 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

EXPERIMENT NO:-4

AIM: Implementation of Fuzzy Controller (Washing Machine).


OBJECTIVE: To design and implement a fuzzy logic controller that determines the wash time of
a washing machine based on inputs such as dirtiness of clothes and load size.
OUTCOME: After performing this practical, students will be able to understand the working of
fuzzy logic controllers and their application in real-world appliances like washing machines.
THEORY: Fuzzy Logic in Washing Machines:
Modern washing machines use fuzzy logic control to automatically adjust washing parameters
instead of relying only on fixed timers.
Inputs:

• Dirtiness of clothes (low, medium, high)


• Load size (small, medium, large)
Output:

• Wash time (short, medium, long)


Example Rules:

• IF dirtiness is low AND load is small THEN wash time is short • IF dirtiness is
medium OR load is medium THEN wash time is medium • IF dirtiness is
high AND load is large THEN wash time is long Working:
1. Fuzzification: Inputs (dirt, load) are converted into membership values.
2. Inference (Rule Evaluation): Fuzzy rules decide the strength of each possible output.
3. Defuzzification: A crisp wash time is calculated (e.g., 42 minutes).
This makes the washing process efficient, adaptive, and user-friendly. Unlike traditional machines
that rely on fixed programs, fuzzy-based machines adjust automatically to varying conditions of
laundry.
CODE:
import [Link].*; public class FuzzyWashingMachine { // Triangular

Membership Function public static double triangular(double x, double

a, double b, double c) {

NAME:-Akash 9 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

if (x > a && x < b)

return (x - a) / (b - a);

else if (x >= b && x < c)

return (c - x) / (c - b);

else if (x == b) return

1; else return 0;

// Fabric Membership public static Map<String, Double>

fabricMembership(double fabric) { Map<String, Double> fabricMap

= new HashMap<>(); [Link]("cotton", triangular(fabric, 0, 1,

2)); [Link]("synthetic", triangular(fabric, 1, 2, 3));

[Link]("woolen", triangular(fabric, 2, 3, 4)); return

fabricMap;} // Dirt Membership public static Map<String, Double>

dirtMembership(double dirt) { Map<String, Double> dirtMap = new

HashMap<>(); [Link]("low", triangular(dirt, 0, 2, 5));

[Link]("medium", triangular(dirt, 3, 5, 7)); [Link]("high",

triangular(dirt, 6, 8, 10)); return dirtMap; }

// Temperature Membership
public static Map<String, Double> tempMembership(double temp) {

Map<String, Double> tempMap = new HashMap<>();

[Link]("cold", triangular(temp, 0, 20, 40));

[Link]("warm", triangular(temp, 30, 50, 70));

[Link]("hot", triangular(temp, 60, 80, 100)); return tempMap;

NAME:-Akash 10 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

// Rule class to hold fuzzy rule

outputs static class Rule { double

condition; int washTime; int

rpm; int dryTime; int

temperature;

Rule(double condition, int washTime, int rpm, int dryTime, int temperature)

{ [Link] = condition; [Link] = washTime;

[Link] = rpm; [Link] = dryTime; [Link] =

temperature;

}// Apply fuzzy rules

public static Rule washingRules(Map<String, Double> fabric, Map<String, Double> dirt,


Map<String, Double> temp) {

List<Rule> rules = new ArrayList<>();

[Link](new Rule([Link]([Link]("cotton"), [Link]("low")), 25, 600, 20, 30));

[Link](new Rule([Link]([Link]([Link]("synthetic"), [Link]("medium")),


[Link]("warm")), 35, 700, 25, 40));

[Link](new Rule([Link]([Link]([Link]("woolen"), [Link]("high")),


[Link]("cold")), 55, 400, 35, 25)); [Link](new Rule([Link]([Link]("cotton"),

[Link]("high")), 50, 800, 30, 50)); [Link](new Rule([Link]([Link]("synthetic"),

[Link]("low")), 20, 900, 15, 35)); [Link](new Rule([Link]([Link]("woolen"),

[Link]("medium")), 40, 500, 25, 30)); Rule bestRule = null; double bestStrength = 0;

for (Rule r : rules) { if ([Link] > bestStrength) { bestStrength =

[Link]; bestRule = r;

NAME:-Akash 11 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

if (bestRule == null) { bestRule =

new Rule(0, 30, 600, 20, 40);

return bestRule;

// Main function to process fuzzy washing public static void washingMachine(double

fabricInput, double dirtInput, double tempInput) {

Map<String, Double> fabricFuzzy = fabricMembership(fabricInput);


Map<String, Double> dirtFuzzy = dirtMembership(dirtInput);

Map<String, Double> tempFuzzy = tempMembership(tempInput);

Rule result = washingRules(fabricFuzzy, dirtFuzzy, tempFuzzy);

[Link]("\n--- Washing Machine Fuzzy Output ---");

[Link]("Wash Time: " + [Link] + " minutes");

[Link]("Spin Speed: " + [Link] + " RPM");

[Link]("Dry Time: " + [Link] + " minutes");

[Link]("Water Temperature: " + [Link] + " °C");

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter fabric type (1=cotton, 2=synthetic, 3=woolen):

"); double fabricInput = [Link](); [Link]("Enter

dirt level (0-10): "); double dirtInput = [Link]();

NAME:-Akash 12 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

[Link]("Enter water temperature (0-100 °C): ");

double tempInput = [Link]();

washingMachine(fabricInput, dirtInput, tempInput);

[Link]();

OUTPUT:

CONCLUSION:
A fuzzy controller for a washing machine was designed, proving how fuzzy logic enables
adaptive and efficient control in real-life appliances.

NAME:-Akash 13 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

EXPERIMENT NO:- 5

AIM: To implement the Perceptron Learning Algorithm using Python.


OBJECTIVE:

• To understand the working principle of the Perceptron Learning Algorithm.


• To implement a single-layer perceptron model for binary classification.
• To observe how weights are updated during the learning process.

OUTCOME:

After completing this experiment, students will be able to:

• Explain the concept of the perceptron and its learning rule.


• Implement perceptron training using Python.
• Classify linearly separable data using the trained perceptron model.

THEORY:

The Perceptron is the simplest type of artificial neural network used for binary classification. It
consists of input nodes, weights, a bias, and an activation function (usually a step function).

Working Principle:

1. The perceptron takes multiple inputs 𝑥1, 𝑥2, . . . , 𝑥𝑛and assigns each input a weight 𝑤1,
𝑤2, . . . , 𝑤𝑛.
2. It computes a weighted sum:

𝑦 = ∑(𝑤𝑖 × 𝑥𝑖) + 𝑏

3. The output is passed through an activation function (usually a step function):

1, if 𝑦 ≥ 0
𝑓(𝑦) = {
0, if 𝑦 < 0

4. The weights are updated using the Perceptron Learning Rule:

𝑤𝑖(𝑛𝑒𝑤) = 𝑤𝑖(𝑜𝑙𝑑) + 𝜂 × (𝑡 − 𝑜) × 𝑥𝑖

NAME:-Akash 14 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

where
o 𝜂= learning rate (0 < η ≤
1) o 𝑡= target output o
𝑜= actual output

This process continues iteratively until all patterns are correctly classified or a maximum
number of epochs is reached.

CODE (Python):
# Implementation of Perceptron Learning Algorithm

import numpy as np

# Input data for AND logic gate


X = [Link]([[0, 0],
[0, 1],
[1, 0],
[1, 1]])

# Target output for AND gate


Y = [Link]([0, 0, 0, 1])

# Initialize weights and bias


weights = [Link]([Link][1])
bias = 0
learning_rate = 0.1

# Training the perceptron


for epoch in range(10): # number of
iterations print(f"\nEpoch {epoch+1}")
for i in range(len(X)):
net_input = [Link](X[i], weights) + bias
predicted = 1 if net_input >= 0 else 0
error = Y[i] - predicted

# Update rule
weights += learning_rate * error * X[i]
bias += learning_rate * error

NAME:-Akash 15 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

print(f"Input: {X[i]}, Target: {Y[i]}, Predicted: {predicted}, Weights: {weights}, Bias:


{bias}")

print("\nFinal Weights:", weights)


print("Final Bias:", bias)

# Testing for i in
range(len(X)):
result = 1 if [Link](X[i], weights) + bias >= 0 else 0
print(f"Input: {X[i]} => Output: {result}")
OUTPUT:

CONCLUSION:

The Perceptron Learning Algorithm successfully learned the AND logic gate operation.
It adjusted the weights and bias after several iterations to correctly classify the inputs.
This demonstrates that a single-layer perceptron can classify linearly separable data
effectively.

NAME:-Akash 16 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

EXPERIMENT NO:- 6

AIM: To implement the K-Means Clustering Algorithm for unsupervised learning using
Python.

OBJECTIVE:

• To understand the concept and working of the K-Means clustering algorithm.


• To apply K-Means clustering to group unlabeled data into clusters.
• To visualize and analyze the clustering results.

OUTCOME:

After completing this experiment, students will be able to:

• Explain the working principle of K-Means clustering.


• Implement K-Means using Python and libraries like sklearn.
• Identify and visualize clusters in a given dataset.
• Understand how unsupervised learning can classify data without labels.

THEORY:

K-Means Clustering is an unsupervised machine learning algorithm used to group a set of


data points into K distinct, non-overlapping clusters.
It minimizes the sum of squared distances between data points and their respective cluster
centroids.

Steps of the K-Means Algorithm:

1. Select the number of clusters (K).


2. Initialize centroids: Randomly choose K initial centroids.
3. Assign data points: Each data point is assigned to the nearest centroid (using Euclidean
distance).
4. Update centroids: Calculate the new centroid of each cluster by averaging the points in
that cluster.
5. Repeat: Steps 3 and 4 are repeated until the centroids stop changing or reach a
convergence condition.

NAME:-Akash 17 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

Mathematical Formula:

The objective function to minimize:


𝐽=∑ ∑ ∣∣ 𝑥𝑗 − 𝜇𝑖 ∣∣2
𝑖=1 𝑥𝑗∈𝐶𝑖

where

• 𝜇𝑖= centroid of cluster 𝐶𝑖


• ∣∣ 𝑥𝑗 − 𝜇𝑖 ∣∣2= Euclidean distance between a data point and its centroid.

CODE (Python):

# Implementation of K-Means Clustering

Algorithm import numpy as np import

[Link] as plt from [Link]

import KMeans from [Link] import

make_blobs

# Generate sample data

X, y = make_blobs(n_samples=200, centers=3, cluster_std=0.70, random_state=0)

# Plot initial data [Link](X[:, 0],

X[:, 1], s=30) [Link]("Input Data

Points (Unlabeled)") [Link]()

# Apply KMeans Clustering

kmeans = KMeans(n_clusters=3)

[Link](X)

# Get cluster centers and labels

centers = kmeans.cluster_centers_

NAME:-Akash 18 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

labels = kmeans.labels_ # Plot

clustered data [Link](X[:, 0], X[:,

1], c=labels, cmap='rainbow', s=30)

[Link](centers[:, 0], centers[:, 1],

c='black', marker='X', s=200)

[Link]("K-Means Clustering

Result") [Link]() print("Cluster

Centers:\n", centers)

OUTPUT:

Graphical Output:

• Plot 1: Unlabeled data points (scattered).


• Plot 2: Data points grouped into 3 clusters, each with a distinct color.
• Centroids: Marked by large black “X” symbols in the plot.

CONCLUSION:

The K-Means Clustering Algorithm successfully grouped the unlabeled data into three
distinct clusters based on their similarity.
This experiment demonstrates the power of unsupervised learning in discovering natural
groupings within data without prior labels.
It is widely used in applications such as image segmentation, customer segmentation, and
pattern recognition.

NAME:-Akash 19 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

EXPERIMENT NO:- 7

AIM: To implement a Simple Genetic Algorithm (GA) for solving an optimization problem.

OBJECTIVE:

• To understand the concept and working of genetic algorithms.


• To apply GA techniques for solving an optimization problem.
• To observe how selection, crossover, and mutation help in finding optimal solutions.

OUTCOME:

After completing this experiment, students will be able to:

• Explain the principles of evolutionary computation.


• Implement a simple genetic algorithm in Python.
• Apply GA for optimization problems and visualize convergence.
• Understand how GA evolves better solutions over generations.

THEORY:

A Genetic Algorithm (GA) is a search and optimization technique based on the principles of
natural selection and genetics.
It works by evolving a population of candidate solutions toward better solutions over multiple
generations.

Basic Steps of a Genetic Algorithm:

1. Initialization:
Randomly generate an initial population of possible solutions.
2. Fitness Evaluation:
Evaluate each individual’s fitness based on how well it solves the problem.
3. Selection:
Select the fittest individuals to reproduce (based on fitness score).
4. Crossover (Recombination):
Combine parts of two parent chromosomes to produce offspring.
5. Mutation:
Introduce small random changes to offspring to maintain diversity.
6. Replacement:
Form a new generation by replacing the old population with new offspring.
7. Termination:

NAME:-Akash 20 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

Repeat steps 2–6 until a stopping criterion (like max generations or optimal fitness) is
met.

Applications:

• Function optimization
• Scheduling problems
• Feature selection
• Neural network training CODE (Python): import numpy as np

# Define the fitness function (maximize f(x) =

x^2) def fitness(x): return x**2

# Create initial population (random integers)

population_size = 6 population = [Link](0, 31,

size=population_size) print("Initial Population:",

population)

# Parameters num_generations = 10

mutation_rate = 0.1 for generation in

range(num_generations):

# Calculate fitness

fitness_values = fitness(population)

# Selection (select top 50% individuals)


sorted_indices = [Link](-fitness_values) selected =

population[sorted_indices][:population_size // 2]

NAME:-Akash 21 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

# Crossover (single-point)

offspring = [] for i in range(0,

len(selected), 2):

parent1, parent2 = selected[i], selected[(i+1) %

len(selected)] crossover_point = [Link](1, 5)

mask = (1 << crossover_point) - 1 child1 = (parent1 &

mask) | (parent2 & ~mask) child2 = (parent2 & mask) |

(parent1 & ~mask) [Link]([child1, child2] #

Mutation (flip a random bit) for i in range(len(offspring)):

if [Link]() < mutation_rate:

mutation_bit = 1 << [Link](0, 5)

offspring[i] ^= mutation_bit # XOR bit flip # New

population = selected parents + new offspring population

= [Link](offspring) # Display generation info best =

[Link](fitness(population)) print(f"Generation

{generation+1}: Best Fitness = {best}") print("\nFinal

Population:", population) print("Best Solution:",

population[[Link](fitness(population))])

NAME:-Akash 22 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

OUTPUT:

CONCLUSION:

The Genetic Algorithm successfully optimized the given problem by evolving better solutions
over generations.
Through processes of selection, crossover, and mutation, the algorithm gradually improved
the population’s fitness and found an optimal solution.
This experiment demonstrates how evolutionary algorithms can be used effectively for solving
optimization problems in machine learning and AI.

NAME:-Akash 23 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

EXPERIMENT NO:- 8

AIM: To study the architecture and working of Adaptive Neuro-Fuzzy Inference System
(ANFIS).

INTRODUCTION: Adaptive Neuro-Fuzzy Inference System (ANFIS) is a hybrid intelligent


system that combines the learning capability of Artificial Neural Networks (ANN) with the
reasoning capability of Fuzzy Logic. It can automatically generate fuzzy rules and membership
functions through training data, thereby improving decision-making accuracy. ANFIS uses a
Sugeno-type fuzzy inference system and learns through a hybrid learning algorithm that
combines Least Squares Estimation (LSE) and Backpropagation (BP).

CODE:

import numpy as np import skfuzzy as fuzz


from skfuzzy import control as ctrl x =
[Link]([Link](0, 11, 1), 'x') y =
[Link]([Link](0, 11, 1), 'y') z =
[Link]([Link](0, 26, 1), 'z')
x['low'] = [Link]([Link], [0, 0, 5])
x['high'] = [Link]([Link], [5, 10, 10])
y['low'] = [Link]([Link], [0, 0, 5])
y['high'] = [Link]([Link], [5, 10, 10])
z['low'] = [Link]([Link], [0, 0, 13])
z['high'] = [Link]([Link], [13, 25, 25])
rule1 = [Link](x['low'] & y['low'], z['low'])
rule2 = [Link](x['high'] | y['high'], z['high'])
anfis_ctrl = [Link]([rule1, rule2])
anfis =
[Link](anfis_ctrl)
[Link]['x'] = 6 [Link]['y'] = 9
[Link]() print([Link]['z'])

OUTPUT:

NAME:-Akash 24 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

EXPERIMENT NO:- 9

AIM: To study optimization techniques that do not require gradient information.

INTRODUCTION: Optimization techniques that do not require gradient information are known
as Derivative-Free Optimization (DFO) or Heuristic Optimization methods. These methods are
particularly useful when the objective function is non-differentiable, discontinuous, or complex.
Examples of such algorithms include Genetic Algorithms (GA), Particle Swarm Optimization
(PSO), Simulated Annealing (SA), and Ant Colony Optimization (ACO). These techniques rely
on stochastic or population-based search strategies rather than mathematical gradients to explore
the solution space and find optimal results.

CODE:

import random
def fitness(x):
return x**2 - 4*x + 4
def mutate(x):
return x + [Link](-1,
1) def crossover(x1, x2): return
(x1 + x2) / 2

population = [[Link](-10, 10) for _ in range(10)]

for _ in range(50):
population = sorted(population, key=lambda x:
fitness(x)) new_population = population[:2] while
len(new_population) < 10:
p1, p2 = [Link](population[:5], 2)
child = crossover(p1, p2)
child = mutate(child)
new_population.append(child)
population = new_population

best = min(population, key=lambda x: fitness(x))


print("Best solution:", best)
print("Minimum value:", fitness(best))

NAME:-Akash 25 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

OUTPUT:

NAME:-Akash 26 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

EXPERIMENT NO:- 10

AIM: To critically review a research paper on soft computing techniques.

INTRODUCTION: A research paper review in soft computing helps in understanding


advancements and applications of intelligent systems like fuzzy logic, neural networks, genetic
algorithms, and hybrid models. Soft computing techniques are designed to handle uncertainty,
imprecision, and partial truth — enabling human-like [Link] experiment focuses
on analyzing a paper based on methodology, performance, and outcomes using simple data
extraction and evaluation through Python.

CODE:

paper_data = {
"title": "A Hybrid Neuro-Fuzzy Model for Data Classification",
"authors": ["Dr. A. Sharma", "Dr. R. Mehta"],
"year": 2023,
"techniques": ["Fuzzy Logic", "Neural Network"],
"accuracy": 92.4,
"dataset": "Iris Dataset"
} def review_paper(data):
if data["accuracy"] > 90:
result = "Excellent performance and reliable model."
else:
result = "Needs improvement in accuracy."
return {
"Title": data["title"],
"Techniques Used": data["techniques"],
"Accuracy": data["accuracy"],
"Review": result
}

output = review_paper(paper_data)
for k, v in [Link]():
print(f"{k}: {v}")

NAME:-Akash 27 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

OUTPUT:

NAME:-Akash 28 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

EXPERIMENT NO:- 11

AIM: To implement a McCulloch-Pitts neuron model for logic gate simulation.

INTRODUCTION: The McCulloch-Pitts neuron is the simplest computational model of a


biological neuron and serves as the foundation of artificial neural networks. It uses binary
inputs and outputs, where the output is determined by applying a threshold (activation)
function to the weighted sum of inputs. This model can simulate basic logic gates like AND,
OR, and NOT, demonstrating how simple neural architectures can represent logical
operations.

CODE:

def McCulloch_Pitts(inputs, weights,


threshold): total = sum(i * w for i, w in
zip(inputs, weights)) if total >= threshold:
return
1 else:
return 0

print("AND Gate
Simulation:") for x1 in
[0, 1]: for x2 in [0, 1]:
output = McCulloch_Pitts([x1, x2], [1, 1], 2)
print(f"Input: ({x1}, {x2}) => Output: {output}")

print("\nOR Gate
Simulation:") for x1 in
[0, 1]: for x2 in [0, 1]:
output = McCulloch_Pitts([x1, x2], [1, 1], 1)
print(f"Input: ({x1}, {x2}) => Output: {output}")

print("\nNOT Gate
Simulation:") for x in [0, 1]:
output = McCulloch_Pitts([x], [-1], 0)
print(f"Input: ({x}) => Output: {output}")

NAME:-Akash 29 ENROLLMENT NO.:- 2210DMBCSE12077


Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore
Shri Vaishnav Institute of Information Technology

OUTPUT:

NAME:-Akash 30 ENROLLMENT NO.:- 2210DMBCSE12077

You might also like