0% found this document useful (0 votes)
29 views9 pages

Python Libraries for Soft Computing

The document introduces Python libraries for soft computing, focusing on neural networks (TensorFlow/Keras/PyTorch), fuzzy logic (scikit-fuzzy), and genetic algorithms (DEAP/PyGAD). It includes code examples demonstrating the implementation of these concepts, such as neural network training, fuzzy logic control systems, and genetic algorithm optimization. Additionally, it covers fuzzy set operations and relations, showcasing their applications in modeling complex systems.

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)
29 views9 pages

Python Libraries for Soft Computing

The document introduces Python libraries for soft computing, focusing on neural networks (TensorFlow/Keras/PyTorch), fuzzy logic (scikit-fuzzy), and genetic algorithms (DEAP/PyGAD). It includes code examples demonstrating the implementation of these concepts, such as neural network training, fuzzy logic control systems, and genetic algorithm optimization. Additionally, it covers fuzzy set operations and relations, showcasing their applications in modeling complex systems.

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

Program – 02

Aim: Introduction to python and its libraries related to soft computing.


1. Neural network
2. Fuzzy logic
3. Genetic algorithms

Theory:
1. Neural Networks (Library: TensorFlow / Keras / PyTorch)
Python provides powerful libraries such as TensorFlow, Keras, and PyTorch to design, train,
and evaluate artificial neural networks. These libraries allow implementation of deep learning
models for tasks like image recognition, natural language processing, and predictive analytics.
They provide pre-built functions, GPU support, and high-level APIs, making neural network
development fast and efficient.

2. Fuzzy Logic (Library: scikit-fuzzy)


Scikit-fuzzy is a Python library for implementing fuzzy logic systems. It supports fuzzy sets,
membership functions, fuzzy inference systems, and defuzzification techniques. Fuzzy logic is
particularly useful in decision-making, control systems, and handling uncertainty in real-world
applications. Python’s scikit-fuzzy makes it easier to model intelligent systems like washing
machine controllers, medical diagnosis systems, and recommendation engines.

3. Genetic Algorithms (Library: DEAP / PyGAD)


Python libraries such as DEAP (Distributed Evolutionary Algorithms in Python) and PyGAD
are widely used for implementing genetic algorithms and other evolutionary computation
techniques. These algorithms mimic the process of natural selection to find optimal or near-
optimal solutions to complex problems. They are used in optimization, scheduling, machine
learning feature selection, and soft computing research.

Code:
1. Neural Network Example in Python

import numpy as np
from [Link] import Sequential
from [Link] import Dense

# Dataset for XOR problem


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

# Build neural network model


model = Sequential()
[Link](Dense(4, input_dim=2, activation='relu'))
[Link](Dense(1, activation='sigmoid'))

# Compile model
[Link](loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# Train model
[Link](X, y, epochs=500, verbose=0)

# Predictions
predictions = [Link](X)
print("Neural Network Output")
print([Link](predictions))

Output:

2. Fuzzy Logic Example in Python

import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl

# Define fuzzy variables


temperature = [Link]([Link](0, 41, 1), 'temperature')
fan_speed = [Link]([Link](0, 101, 1), 'fan_speed')
# Membership functions
temperature['cold'] = [Link]([Link], [0, 0, 20])
temperature['warm'] = [Link]([Link], [10, 20, 30])
temperature['hot'] = [Link]([Link], [20, 40, 40])

fan_speed['low'] = [Link](fan_speed.universe, [0, 0, 50])


fan_speed['medium'] = [Link](fan_speed.universe, [25, 50, 75])
fan_speed['high'] = [Link](fan_speed.universe, [50, 100, 100])

# Fuzzy rules
rule1 = [Link](temperature['cold'], fan_speed['low'])
rule2 = [Link](temperature['warm'], fan_speed['medium'])
rule3 = [Link](temperature['hot'], fan_speed['high'])

# Control system
fan_ctrl = [Link]([rule1, rule2, rule3])
fan_sim = [Link](fan_ctrl)

# Input and computation


fan_sim.input['temperature'] = 28
fan_sim.compute()

print("\nFuzzy Logic Output")


print(f"Temperature: 28°C → Fan Speed: {fan_sim.output['fan_speed']:.2f}%")

Output:
3. Genetic Algorithm Example in Python

import random
from deap import base, creator, tools, algorithms

# Define Fitness and Individual


[Link]("FitnessMax", [Link], weights=(1.0,))
[Link]("Individual", list, fitness=[Link])

toolbox = [Link]()
[Link]("attr_bool", [Link], 0, 1)
[Link]("individual", [Link], [Link], toolbox.attr_bool,
5)
[Link]("population", [Link], list, [Link])

# Evaluation function
def eval_function(individual):
x = int("".join(str(bit) for bit in individual), 2)
return (x**2,)

[Link]("evaluate", eval_function)
[Link]("mate", [Link])
[Link]("mutate", [Link], indpb=0.05)
[Link]("select", [Link], tournsize=3)

# Run Genetic Algorithm


population = [Link](n=20)
[Link](population, toolbox, cxpb=0.5, mutpb=0.2, ngen=20,
verbose=False)

# Get best solution


best_ind = [Link](population, 1)[0]
best_x = int("".join(str(bit) for bit in best_ind), 2)
print("\nGenetic Algorithm Output")
print(f"Best Individual: {best_ind}, x = {best_x}, f(x) = {best_x**2}")

Output:
Conclusion:
In this program, we explored Python’s role in soft computing through its libraries for neural
networks, fuzzy logic, and genetic algorithms. To strengthen understanding, implementations
were also demonstrated using its specialized toolboxes. These examples show how Python
provide powerful environments for building intelligent systems, making them essential tools
in soft computing.
Program - 05
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 Max-Min 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:
import numpy as np

# Define Universe of Discourse


U = [Link]([10, 20, 30, 40, 50, 60])

# Define Membership values for sets A and B


A_membership = [Link]([1.0, 0.8, 0.6, 0.4, 0.2, 0.0])
B_membership = [Link]([0.0, 0.2, 0.7, 1.0, 0.7, 0.2])

# Fuzzy Sets (for display)


FuzzySet_A = [Link]((U, A_membership))
FuzzySet_B = [Link]((U, B_membership))

print("Fuzzy Set A (Young):")


print(FuzzySet_A)

print("\nFuzzy Set B (Middle-Aged):")


print(FuzzySet_B)
# Union (A ∪ B)

Union_membership = [Link](A_membership, B_membership)


print("\nUnion (A or B):")
print(Union_membership)

# Intersection (A ∩ B)
Intersection_membership = [Link](A_membership, B_membership)
print("\nIntersection (A and B):")
print(Intersection_membership)

# Complement of A
Complement_A_membership = 1 - A_membership
print("\nComplement of A (not Young):")
print(Complement_A_membership)

# Difference (A - B)
Difference_membership = [Link](A_membership, 1 - B_membership)
print("\nDifference (A - B):")
print(Difference_membership)

print("\n--- Cartesian Product and Composition ---")


# Fuzzy Sets P and Q
X1 = [Link]([0.2, 0.5, 0.9]) # Set P (x1, x2, x3)
X2 = [Link]([0.4, 0.7]) # Set Q (y1, y2)

# Fuzzy Relation R (Cartesian Product)


Relation_R = [Link]((len(X1), len(X2)))
for i in range(len(X1)):
for j in range(len(X2)):
Relation_R[i, j] = min(X1[i], X2[j])

print("\nFuzzy Relation R (Cartesian Product of P and Q):")


print(Relation_R)

# Define another relation S


Relation_S = [Link]([
[0.6, 0.1],
[0.3, 0.8]
])

# Max-Min Composition of R and S


Composition_Result = [Link]((Relation_R.shape[0], Relation_S.shape[1]))
for i in range(Relation_R.shape[0]):
for j in range(Relation_S.shape[1]):
min_values = [Link](Relation_R[i, :], Relation_S[:, j])
Composition_Result[i, j] = [Link](min_values)

print("\nMax-Min Composition of R and S:")


print(Composition_Result)
Output:

Conclusion:
The program successfully demonstrated various fuzzy set operations such as union,
intersection, complement, and difference. It also computed the Cartesian product of two
fuzzy sets to form a fuzzy relation and applied the max–min composition between two
relations. These operations illustrate how fuzzy relations and compositions can be used to
model complex systems in fuzzy logic, forming the basis for fuzzy reasoning and decision-
making processes.

You might also like