Manual
Manual
Algorithm:
1. Define Fuzzy Sets:
Create two fuzzy sets with elements and their corresponding membership values.
2. Union Operation:
For each element in the fuzzy sets, calculate the maximum membership value between the
two sets.
3. Intersection Operation:
For each element in the fuzzy sets, calculate the minimum membership value between the
two sets.
4. Complement Operation:
For each element in a fuzzy set, subtract the membership value from 1.
5. Difference Operation:
For each element in the fuzzy sets, calculate the difference by subtracting the membership
value of the second set from the first set.
Coding:
# Perform operations
union_result = fuzzy_union(A, B)
intersection_result = fuzzy_intersection(A, B)
complement_result_A = fuzzy_complement(A)
complement_result_B = fuzzy_complement(B)
difference_result = fuzzy_difference(A, B)
# Print results
print("Fuzzy Set A:", A)
print("Fuzzy Set B:", B)
print("Union of A and B:", union_result)
print("Intersection of A and B:", intersection_result)
print("Complement of A:", complement_result_A)
print("Complement of B:", complement_result_B)
print("Difference of A and B:", difference_result)
Output:
Fuzzy Set A: {'a': 0.2, 'b': 0.3, 'c': 0.6, 'd': 0.6}
Fuzzy Set B: {'a': 0.9, 'b': 0.9, 'c': 0.4, 'd': 0.5}
Union of A and B: {'a': 0.9, 'b': 0.9, 'c': 0.6, 'd': 0.6}
Intersection of A and B: {'a': 0.2, 'b': 0.3, 'c': 0.4, 'd': 0.5}
Complement of A: {'a': 0.8, 'b': 0.7, 'c': 0.4, 'd': 0.4}
Complement of B: {'a': 0.1, 'b': 0.1, 'c': 0.6, 'd': 0.5}
Difference of A and B: {'a': 0, 'b': 0, 'c': 0.2, 'd': 0.1}
Result:
This program demonstrates the basic operations on fuzzy sets using Python.
2. Implementation of Fuzzy Relations
Aim:
To implement basic fuzzy relations operations such as Cartesian product, max-min
composition, and max-product composition using Python.
Algorithm:
1. Define Fuzzy Sets:
Create two fuzzy sets with elements and their corresponding membership values.
2. Cartesian Product:
For each pair of elements from the two fuzzy sets, calculate the Cartesian product by taking
the minimum of their membership values.
3. Max-Min Composition:
For each pair of elements from the resulting Cartesian product, calculate the max-min
composition by taking the maximum of the minimum values.
4. Max-Product Composition:
For each pair of elements from the resulting Cartesian product, calculate the max-product
composition by taking the maximum of the product of their membership values.
Coding:
# Define fuzzy sets
A = {'a': 0.2, 'b': 0.3, 'c': 0.6}
B = {'x': 0.9, 'y': 0.4, 'z': 0.5}
# Perform operations
cartesian_product_result = cartesian_product(A, B)
max_min_composition_result = max_min_composition(A, B)
max_product_composition_result = max_product_composition(A, B)
# Print results
print("Fuzzy Set A:", A)
print("Fuzzy Set B:", B)
print("Cartesian Product of A and B:", cartesian_product_result)
print("Max-Min Composition of A and B:", max_min_composition_result)
print("Max-Product Composition of A and B:", max_product_composition_result)
Output:
Fuzzy Set A: {'a': 0.2, 'b': 0.3, 'c': 0.6}
Fuzzy Set B: {'x': 0.9, 'y': 0.4, 'z': 0.5}
Cartesian Product of A and B: {('a', 'x'): 0.2, ('a', 'y'): 0.2, ('a', 'z'): 0.2, ('b', 'x'): 0.3, ('b', 'y'):
0.3, ('b', 'z'): 0.3, ('c', 'x'): 0.6, ('c', 'y'): 0.4, ('c', 'z'): 0.5}
Max-Min Composition of A and B: {('a', 'x'): 0.2, ('a', 'y'): 0.2, ('a', 'z'): 0.2, ('b', 'x'): 0.3, ('b',
'y'): 0.3, ('b', 'z'): 0.3, ('c', 'x'): 0.6, ('c', 'y'): 0.4, ('c', 'z'): 0.5}
Max-Product Composition of A and B: {('a', 'x'): 0.18, ('a', 'y'): 0.08, ('a', 'z'): 0.1, ('b', 'x'):
0.27, ('b', 'y'): 0.12, ('b', 'z'): 0.15, ('c', 'x'): 0.54, ('c', 'y'): 0.24, ('c', 'z'): 0.3}
Result:
This program demonstrates the basic operations on fuzzy relations using Python.
3. Implement De-Morgan’s Law
Aim
To implement De Morgan’s Laws using Python and verify their correctness.
Algorithm
1. Define Boolean Variables:
Create boolean variables for the expressions.
2. Apply De Morgan’s Laws:
De Morgan’s First Law: ¬(P ∧ Q) = ¬P ∨ ¬Q
Coding:
# Print results
print("De Morgan's First Law: ¬(P ∧ Q) = ¬P ∨ ¬Q")
print(f"Left Side: {left_side_1}")
print(f"Right Side: {right_side_1}")
print(f"Law holds: {left_side_1 == right_side_1}\n")
Output
De Morgan's First Law: ¬(P ∧ Q) = ¬P ∨ ¬Q
Left Side: True
Right Side: True
Law holds: True
Result:
This program demonstrates the implementation and verification of De Morgan’s Laws using
Python.
4. Implementation of fuzzy control/ inference system
Aim:
To implement a fuzzy control/inference system using Python, demonstrating the basic
principles of fuzzy logic and inference.
Algorithm:
1. Define Fuzzy Variables:
Create input and output fuzzy variables with their respective membership functions.
2. Define Fuzzy Rules:
Establish a set of fuzzy rules that describe the relationship between input and output
variables.
3. Fuzzification:
Convert crisp input values into degrees of membership for the fuzzy sets.
4. Inference:
Apply the fuzzy rules to the fuzzified inputs to generate fuzzy outputs.
5. Defuzzification:
Convert the fuzzy output sets into a crisp output value.
Coding:
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
# Input values
fan_speed_simulation.input['temperature'] = 25
fan_speed_simulation.input['humidity'] = 65
# Output result
print(f"Fan Speed: {fan_speed_simulation.output['fan_speed']}")
Result:
This program demonstrates the implementation of a simple fuzzy control system using
Python.
5. Maximizing a function using Genetic algorithm
Aim:
To implement a genetic algorithm in Python to maximize a given function.
Algorithm:
1. Define the Problem:
Specify the function to be maximized and the range of input values.
2. Initialize Population:
Create an initial population of potential solutions (chromosomes).
3. Evaluate Fitness:
Define a fitness function to evaluate how well each solution solves the problem.
4. Selection:
Select pairs of solutions based on their fitness to create offspring.
5. Crossover:
Combine pairs of solutions to create new offspring.
6. Mutation:
Introduce random changes to some offspring to maintain genetic diversity.
7. Create New Population:
Replace the old population with the new offspring.
8. Repeat:
Repeat the evaluation, selection, crossover, and mutation steps for a set number of
generations or until a stopping criterion is met.
Coding:
import numpy as np
import matplotlib.pyplot as plt
# Initialize population
def initialize_population(size, bounds):
return np.random.uniform(bounds[0], bounds[1], size)
# Selection
def selection(pop, fitnesses, num_parents):
parents = np.empty((num_parents,))
for i in range(num_parents):
max_fitness_idx = np.where(fitnesses == np.max(fitnesses))
max_fitness_idx = max_fitness_idx[0][0]
parents[i] = pop[max_fitness_idx]
fitnesses[max_fitness_idx] = -99999999
return parents
# Crossover
def crossover(parents, offspring_size):
offspring = np.empty(offspring_size)
crossover_point = np.uint8(offspring_size[0]/2)
for k in range(offspring_size[0]):
parent1_idx = k % parents.shape[0]
parent2_idx = (k+1) % parents.shape[0]
offspring[k] = parents[parent1_idx] + parents[parent2_idx] / 2
return offspring
# Mutation
def mutation(offspring, mutation_rate, bounds):
for idx in range(offspring.shape[0]):
if np.random.rand() < mutation_rate:
random_value = np.random.uniform(bounds[0], bounds[1])
offspring[idx] = offspring[idx] + random_value
return offspring
# Genetic Algorithm
def genetic_algorithm(func, bounds, pop_size, num_generations, mutation_rate):
population = initialize_population(pop_size, bounds)
best_outputs = []
for generation in range(num_generations):
fitnesses = fitness(population)
best_outputs.append(np.max(fitnesses))
parents = selection(population, fitnesses, pop_size//2)
offspring_crossover = crossover(parents, (pop_size - parents.shape[0],))
offspring_mutation = mutation(offspring_crossover, mutation_rate, bounds)
population[0:parents.shape[0]] = parents
population[parents.shape[0]:] = offspring_mutation
return best_outputs, population
# Parameters
bounds = [0, 1]
pop_size = 10
num_generations = 50
mutation_rate = 0.1
# Plot results
plt.plot(best_outputs)
plt.xlabel('Generation')
plt.ylabel('Best Fitness')
plt.title('Genetic Algorithm Optimization')
plt.show()
Result:
This program demonstrates the implementation of a genetic algorithm to maximize a function
using Python.
6. Implementation of two input sine function
Aim:
To implement a function in Python that calculates the sine of two input values and returns
their sum.
Algorithm:
1. Import Necessary Libraries
2. Import the math library to use the sine function.
3. Define the Function:
4. Create a function that takes two input values.
5. Calculate the sine of each input value.
6. Return the sum of the sine values.
7. Test the Function:
8. Call the function with different pairs of input values to verify its correctness.
Coding:
import math
# Define the function to calculate the sine of two inputs and return their sum
def sine_sum(x, y):
sine_x = math.sin(x)
sine_y = math.sin(y)
return sine_x + sine_y
Output:
sine_sum(0, 1.5707963267948966) = 1.0
sine_sum(0.7853981633974483, 0.7853981633974483) = 1.414213562373095
sine_sum(3.141592653589793, 4.71238898038469) = -1.0
Result:
This program demonstrates how to implement and test a function that calculates the sine of
two input values and returns their sum.
7. Implementation of three input nonlinear function
Aim:
To implement a three-input nonlinear function in Python and evaluate it for given inputs.
Algorithm:
1. Define the Nonlinear Function:
2. Create a function that takes three input values and computes the nonlinear expression.
3. Initialize Input Values:
4. Define the input values for the function.
5. Evaluate the Function:
6. Call the function with the input values and compute the result.
7. Display the Result:
8. Print the computed result.
Coding:
import math
Result:
This program demonstrates how to implement and evaluate a three-input nonlinear function
using Python.
8. Implementation of Adaptive Neuro-Fuzzy Inference System
Aim:
To implement an Adaptive Neuro-Fuzzy Inference System (ANFIS) using Python,
demonstrating the integration of neural networks and fuzzy logic for inference and control.
Algorithm
Define Fuzzy Variables:
Create input and output fuzzy variables with their respective membership functions.
Initialize ANFIS Model:
Set up the ANFIS model structure, including the number of membership functions and rules.
Train the ANFIS Model:
Use a dataset to train the ANFIS model, adjusting the parameters to minimize the error
between predicted and actual outputs.
Evaluate the Model:
Test the trained model on a validation dataset to evaluate its performance.
Make Predictions:
Use the trained ANFIS model to make predictions on new data.
Coding:
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
from anfis import ANFIS
# Print results
print("Training complete. Model evaluation:")
print(predicted_Z)
# Plot results
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, predicted_Z, cmap='viridis')
plt.show()
Result:
This program demonstrates the implementation of an Adaptive Neuro-Fuzzy Inference
System using Python.