0% found this document useful (0 votes)
34 views21 pages

Manual

lab manual

Uploaded by

720823103021
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)
34 views21 pages

Manual

lab manual

Uploaded by

720823103021
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/ 21

1.

Implementation of Simple Fuzzy Operations


Aim:
To implement basic fuzzy set operations such as union, intersection, complement, and
difference using Python.

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:

# Define fuzzy sets


A = {'a': 0.2, 'b': 0.3, 'c': 0.6, 'd': 0.6}
B = {'a': 0.9, 'b': 0.9, 'c': 0.4, 'd': 0.5}

# Union of two fuzzy sets


def fuzzy_union(A, B):
union = {}
for key in A:
union[key] = max(A[key], B[key])
return union

# Intersection of two fuzzy sets


def fuzzy_intersection(A, B):
intersection = {}
for key in A:
intersection[key] = min(A[key], B[key])
return intersection

# Complement of a fuzzy set


def fuzzy_complement(A):
complement = {}
for key in A:
complement[key] = 1 - A[key]
return complement

# Difference of two fuzzy sets


def fuzzy_difference(A, B):
difference = {}
for key in A:
difference[key] = max(0, A[key] - B[key])
return difference

# 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}

# Cartesian Product of two fuzzy sets


def cartesian_product(A, B):
product = {}
for a_key, a_value in A.items():
for b_key, b_value in B.items():
product[(a_key, b_key)] = min(a_value, b_value)
return product

# Max-Min Composition of two fuzzy sets


def max_min_composition(A, B):
composition = {}
for a_key, a_value in A.items():
for b_key, b_value in B.items():
composition[(a_key, b_key)] = max(min(a_value, b_value), composition.get((a_key,
b_key), 0))
return composition

# Max-Product Composition of two fuzzy sets


def max_product_composition(A, B):
composition = {}
for a_key, a_value in A.items():
for b_key, b_value in B.items():
composition[(a_key, b_key)] = max(a_value * b_value, composition.get((a_key,
b_key), 0))
return composition

# 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

De Morgan’s Second Law: ¬(P ∨ Q) = ¬P ∧ ¬Q


3. Verify the Laws:
Evaluate both sides of the equations for different combinations of boolean values.

Coding:

# Define boolean variables


P = True
Q = False

# De Morgan's First Law: ¬(P ∧ Q) = ¬P ∨ ¬Q


left_side_1 = not (P and Q)
right_side_1 = (not P) or (not Q)

# De Morgan's Second Law: ¬(P ∨ Q) = ¬P ∧ ¬Q


left_side_2 = not (P or Q)
right_side_2 = (not P) and (not Q)

# 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")

print("De Morgan's Second Law: ¬(P ∨ Q) = ¬P ∧ ¬Q")


print(f"Left Side: {left_side_2}")
print(f"Right Side: {right_side_2}")
print(f"Law holds: {left_side_2 == right_side_2}")

Output
De Morgan's First Law: ¬(P ∧ Q) = ¬P ∨ ¬Q
Left Side: True
Right Side: True
Law holds: True

De Morgan's Second Law: ¬(P ∨ Q) = ¬P ∧ ¬Q


Left Side: False
Right Side: False
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

# Define fuzzy variables


temperature = ctrl.Antecedent(np.arange(0, 41, 1), 'temperature')
humidity = ctrl.Antecedent(np.arange(0, 101, 1), 'humidity')
fan_speed = ctrl.Consequent(np.arange(0, 101, 1), 'fan_speed')

# Define membership functions for temperature


temperature['cold'] = fuzz.trimf(temperature.universe, [0, 0, 20])
temperature['warm'] = fuzz.trimf(temperature.universe, [10, 20, 30])
temperature['hot'] = fuzz.trimf(temperature.universe, [20, 40, 40])

# Define membership functions for humidity


humidity['low'] = fuzz.trimf(humidity.universe, [0, 0, 50])
humidity['medium'] = fuzz.trimf(humidity.universe, [25, 50, 75])
humidity['high'] = fuzz.trimf(humidity.universe, [50, 100, 100])

# Define membership functions for fan speed


fan_speed['low'] = fuzz.trimf(fan_speed.universe, [0, 0, 50])
fan_speed['medium'] = fuzz.trimf(fan_speed.universe, [25, 50, 75])
fan_speed['high'] = fuzz.trimf(fan_speed.universe, [50, 100, 100])

# Define fuzzy rules


rule1 = ctrl.Rule(temperature['cold'] & humidity['low'], fan_speed['low'])
rule2 = ctrl.Rule(temperature['cold'] & humidity['medium'], fan_speed['medium'])
rule3 = ctrl.Rule(temperature['cold'] & humidity['high'], fan_speed['high'])
rule4 = ctrl.Rule(temperature['warm'] & humidity['low'], fan_speed['medium'])
rule5 = ctrl.Rule(temperature['warm'] & humidity['medium'], fan_speed['medium'])
rule6 = ctrl.Rule(temperature['warm'] & humidity['high'], fan_speed['high'])
rule7 = ctrl.Rule(temperature['hot'] & humidity['low'], fan_speed['high'])
rule8 = ctrl.Rule(temperature['hot'] & humidity['medium'], fan_speed['high'])
rule9 = ctrl.Rule(temperature['hot'] & humidity['high'], fan_speed['high'])

# Create control system


fan_speed_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8,
rule9])
fan_speed_simulation = ctrl.ControlSystemSimulation(fan_speed_ctrl)

# Input values
fan_speed_simulation.input['temperature'] = 25
fan_speed_simulation.input['humidity'] = 65

# Compute the result


fan_speed_simulation.compute()

# Output result
print(f"Fan Speed: {fan_speed_simulation.output['fan_speed']}")

# Visualize the result


temperature.view()
humidity.view()
fan_speed.view(sim=fan_speed_simulation)
Output:
Fan Speed: 70.0

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

# Define the function to be maximized


def func(x):
return x * np.sin(10 * np.pi * x) + 1

# Define the fitness function


def fitness(x):
return func(x)

# 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

# Run Genetic Algorithm


best_outputs, population = genetic_algorithm(func, bounds, pop_size, num_generations,
mutation_rate)

# Plot results
plt.plot(best_outputs)
plt.xlabel('Generation')
plt.ylabel('Best Fitness')
plt.title('Genetic Algorithm Optimization')
plt.show()

# Print the best solution


best_solution = population[np.argmax(fitness(population))]
print(f"Best solution: x = {best_solution}, f(x) = {func(best_solution)}")
Output:
Best solution: x = 0.9, f(x) = 1.5

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

# Test the function with different input values


x1, y1 = 0, math.pi / 2
x2, y2 = math.pi / 4, math.pi / 4
x3, y3 = math.pi, 3 * math.pi / 2

print(f"sine_sum({x1}, {y1}) = {sine_sum(x1, y1)}")


print(f"sine_sum({x2}, {y2}) = {sine_sum(x2, y2)}")
print(f"sine_sum({x3}, {y3}) = {sine_sum(x3, y3)}")

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

# Define the nonlinear function


def nonlinear_function(x, y, z):
return x * math.sin(y) + y * math.cos(z) + z * math.exp(x)

# Initialize input values


x = 1.0
y = 2.0
z = 3.0

# Evaluate the function


result = nonlinear_function(x, y, z)

# Display the result


print(f"The result of the nonlinear function for inputs x={x}, y={y}, z={z} is: {result}")
Output:
The result of the nonlinear function for inputs x=1.0, y=2.0, z=3.0 is: 23.08060461173628

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

# Define fuzzy variables


x = np.linspace(-10, 10, 100)
y = np.linspace(-10, 10, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

# Define membership functions


mf = [
[fuzz.gaussmf(x, -5, 1), fuzz.gaussmf(x, 0, 1), fuzz.gaussmf(x, 5, 1)],
[fuzz.gaussmf(y, -5, 1), fuzz.gaussmf(y, 0, 1), fuzz.gaussmf(y, 5, 1)]
]

# Initialize ANFIS model


anfis = ANFIS(X, Y, Z, mf)

# Train the ANFIS model


anfis.train(epochs=100, learning_rate=0.01)

# Evaluate the model


predicted_Z = anfis.predict(X, Y)

# 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.

You might also like