Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 9

Ex.

Name: Performing Union, Intersection and Complement operations


Aim :
To write a Program in MATLAB to perform union, intersection and complement
operations of fuzzy set.
Algorithm:

1. Read the membership values of two fuzzy sets.


2. Perform union operation by using max( ) function.
3. Perform intersection operation by using min( ) function.
4. Perform complement operation by subtracting membership value from 1
5. Display the result.

Program:
% Enter the membership value of fuzzy set
u = input (‘Enter the membership value of First Fuzzy set’);
v = input (‘Enter the membership value of Second Fuzzy set’);
%performs Union, Intersection and Complement operations
w=max (u, v);
p=min (u, v);
q1=1-u;
q2=1-v;
%Display Output
disp(‘Union of Two Fuzzy sets’);
disp(w);
disp(‘Intersection of Two Fuzzy sets’);
disp(p);
disp(‘Complement of First Fuzzy set’);
disp(q1);
disp(‘Complement of Second Fuzzy set’);
disp(q2);
Sample Input and Output:

Enter the membership value of First Fuzzy set [0.3 0.4]


Enter the membership value of Second Fuzzy set [0.1 0.7]
Union of Two Fuzzy sets
0.3000. 0.7000
Intersection of Two fuzzy sets
0.1000 0.4000.
Complement of First Fuzzy set
0.7000 0.6000.
Complement of Second Fuzzy set
0.9000 0.3000.

Discussion:
Thus, the MATLAB program to perform Union, Intersection and Complement operations

of two Fuzzy sets has been executed successfully and the output is verified.

Ex. No: PCCAIML 693/02


Ex. Name: Implementation of De-Morgan’s Law
Aim:
To write a Program in MATLAB to implement De-Morgan’s law.
Algorithm:
1. Read the membership values of two fuzzy set.
2. Perform Union operation by using max() function and take the complement for the
fuzzy set.
3. Perform Intersection operation by using min() function and take the complement.
4. Perform Complement operation for the both fuzzy sets.
5. Perform Intersection operation and Union operation for the Complements of fuzzy
set.
6. Verify the formula and display the result.
Program:
% Enter the membership values of fuzzy set
u = input (‘Enter the membership values of first fuzzy set’);
v = input (‘Enter the membership values of second fuzzy set’);
%To perform operation
w=max (u, v);
p=min (u, v);
q1=1-u;
q2=1-v;
x1=1-w;
x2=min(q1,q2);
y1=1-p;
y2=max(q1-q2);
%Display Output
disp(‘Union of two fuzzy sets ’);
disp(w);
disp(‘Intersection of two fuzzy sets ’);
disp(p);
disp(‘Complement of first fuzzy set ’);
disp(q1);
disp(‘Complement of second fuzzy set ’);
disp(q2);
disp(‘De-Morgan’s Law’);
disp(‘LHS’);
disp(x1);
disp(‘RHS’);
disp(x2);
disp(LHS);
disp(y1);
disp(‘RHS’);
disp(y2);
Sample Input and output:
Enter the membership values of first fuzzy set [0.3 0.4]
Enter the membership values of second fuzzy set [0.2 0.5]
Union of two fuzzy sets

0.3000. 0.5000
Intersection of two fuzzy sets
0.3000 0.4000.
Complement of first fuzzy set
0.7000 0.6000.
Complement of second fuzzy set
0.8000 0.5000.
De-Morgan’s Law: (i) (A ∪ B)' = A' ∩ B' and (ii) (A ∩ B)' = A'
∪ B'
Output: (0.3 0.5)’ = (0.7 0.6) ∩ (0.8 0.5) = (0.7 0.5)

Discussion:
Thus, the MATLAB program for implementation of De-Morgan’s has been executed
successfully and the output is verified.

Ex. No: PCCAIML 693/03


Ex. Name: Simple Fuzzy Set Operations
Aim:
To write a MATLAB program to find algebraic sum, algebraic subtraction, algebraic
product, bounded sum, bounded subtraction and bounded product of two fuzzy sets.
Algorithm:
1. Read the values of the two fuzzy sets.
2. Perform the algebraic sum operation by,
A + B = (a + b) – (a * b)

3. Perform the algebraic subtraction operation by,


A – B = (a + b`) where b`= 1- b
4. Perform the algebraic product operation by,

A * B = (a * b)

5. Perform the bounded sum operation by,


A ⊕B = min [1, (a + b)]

6. Perform bounded subtraction operation by,

A ⊝B= max [0, (a - b)]

7. Perform bounded product operation by,


A ⊙B = max [0, (a + b - 1)]

8. Display the results


Program:
a= input(‘Enter the fuzzy set a’ )
b= input(‘Enter the fuzzy set b’)
c= a + b
d= a * b
as= c – d
e= 1 – b
ad= a + e
f= a – b
bs= min (1, c)
bd= max (0, f)

g= c – 1
bp= max (0,g)
disp(‘The algebraic sum’)
disp(as)
disp(‘The algebraic difference’)
disp(ad)
disp(‘The algebraic product’)
disp(d)
disp(‘The bounded sum’)
disp(bs)
disp(‘The bounded difference’)
disp (bd)
disp(‘The bounded product’)
disp(bp)

Output:
Enter fuzzy set a [1 0.5]
Enter fuzzy set b [0.4 0.2]
The algebraic sum
[1.0000 0.6000 ]
The algebraic difference
[1 0.9000]
The algebraic product
[0.4000 0.1000]
The bounded sum
[1.0000 0.7000]
The bounded difference
[0.6000 0.3000]
The bounded product
[0.4000 0]

Discussion:
Thus, a program to perform simple fuzzy set operations has been executed and
successfully
verified.

Gradient descent optimization based on ACO


import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Define the function to be minimized (a simple quadratic function)
def f(x, y):
return x**2 + y**2
# Define the partial derivatives of the function with respect to x and y
def df_dx(x, y):
return 2 * x
def df_dy(x, y):
return 2 * y
# Define the gradient descent algorithm
def gradient_descent(start_x, start_y, learning_rate, num_iterations):
# Initialize the parameters
x = start_x
y = start_y
history = []
# Perform the gradient descent iterations
for i in range(num_iterations):
# Calculate the gradients
grad_x = df_dx(x, y)
grad_y = df_dy(x, y)
# Update the parameters
x = x - learning_rate * grad_x
y = y - learning_rate * grad_y
# Save the history of the parameters
history.append((x, y, f(x, y)))
return x, y, f(x, y), history
# Define the meshgrid for plotting the function
x_range = np.arange(-10, 10, 0.1)
y_range = np.arange(-10, 10, 0.1)
X, Y = np.meshgrid(x_range, y_range)
Z = f(X, Y)
# Perform gradient descent and plot the results
start_x, start_y = 8, 8
learning_rate = 0.1
num_iterations = 20
x_opt, y_opt, f_opt, history = gradient_descent(start_x, start_y,
learning_rate, num_iterations)
fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='coolwarm')
ax.scatter(*zip(*history), c='r', marker='o')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('f(x, y)')
plt.show()

TSP with ACO

Installation
From PyPi
pip install aco
Using Poetry
poetry add aco
Usage
AntColony(
nodes,
start=None,
ant_count=300,
alpha=0.5,
beta=1.2,
pheromone_evaporation_rate=0.40,
pheromone_constant=1000.0,
iterations=300,
)
Travelling Salesman Problem
import matplotlib.pyplot as plt
import random
from aco import AntColony
plt.style.use("dark_background")
COORDS = (
(20, 52),
(43, 50),
(20, 84),
(70, 65),
(29, 90),
(87, 83),
(73, 23),
)
def random_coord():
r = random.randint(0, len(COORDS))
return r
def plot_nodes(w=12, h=8):
for x, y in COORDS:

plt.plot(x, y, "g.", markersize=15)


plt.axis("off")
fig = plt.gcf()
fig.set_size_inches([w, h])
def plot_all_edges():
paths = ((a, b) for a in COORDS for b in COORDS)
for a, b in paths:
plt.plot((a[0], b[0]), (a[1], b[1]))
plot_nodes()
colony = AntColony(COORDS, ant_count=300, iterations=300)
optimal_nodes = colony.get_path()
for i in range(len(optimal_nodes) - 1):
plt.plot(
(optimal_nodes[i][0], optimal_nodes[i + 1][0]),
(optimal_nodes[i][1], optimal_nodes[i + 1][1]),
)
plt.show()
(1) Design of McCullach Pit Model
Step1: Generate a vector of inputs and a vector of outputs
import numpy as np
np.random.seed(seed=0)
I = np.random.choice([0,1], 3)# generate random vector I, sampling from {0,1}
W = np.random.choice([-1,1], 3) # generate random vector W, sampling from {-1,1}
print(f'Input vector:{I}, Weight vector:{W}')

Step 2: Compute the dot products between the vector of inputs and weights
dot = I @ W
print(f'Dot product: {dot}')
Step 3: Define the threshold activation function
def linear_threshold_gate(dot: int, T: float) -> int:
'''Returns the binary threshold output'''
if dot >= T:
return 1
else:
return 0

Step 4: Compute the output based on the threshold


T = 1
activation = linear_threshold_gate(dot, T)
print(f'Activation: {activation}')

Step 5: Deactivate the firing of output with T=3


T = 3
activation = linear_threshold_gate(dot, T)
print(f'Activation: {activation}')

(2) AND Function design with McCulloch-Pitts model


Step1: Generate a vector of inputs and a vector of outputs
# matrix of inputs
input_table = np.array([
[0,0], # both no
[0,1], # one no, one yes
[1,0], # one yes, one no
[1,1] # bot yes
])
print(f'input table:\n{input_table}')
# array of weights
weights = np.array([1,1])
print(f'weights: {weights}')

Step 2: Compute the dot products between the matrix of inputs and weights
# dot product matrix of inputs and weights
dot_products = input_table @ weights
print(f'Dot products: {dot_products}')
Step 3: Define the threshold activation function
def linear_threshold_gate(dot: int, T: float) -> int:
'''Returns the binary threshold output'''
if dot >= T:
return 1
else:
return 0
Step 4: Compute the output based on the threshold
T = 2
for i in range(0,4):
activation = linear_threshold_gate(dot_products[i], T)
print(f'Activation: {activation}')

(3) OR Function design with McCulloch-Pitts model


Step1: Generate a vector of inputs and a vector of outputs
# matrix of inputs
input_table = np.array([
[0,0], # both no
[0,1], # one no, one yes
[1,0], # one yes, one no
[1,1] # bot yes
])
print(f'input table:\n{input_table}')
# array of weights
weights = np.array([1,1])
print(f'weights: {weights}')
Step 2: Compute the dot products between the matrix of inputs and weights
# dot product matrix of inputs and weights
dot_products = input_table @ weights
print(f'Dot products: {dot_products}')
Step 3: Define the threshold activation function
def linear_threshold_gate(dot: int, T: float) -> int:
'''Returns the binary threshold output'''
if dot >= T:
return 1
else:
return 0

Step 4: Compute the output based on the threshold


T = 1
for i in range(0,4):
activation = linear_threshold_gate(dot_products[i], T)
print(f'Activation: {activation}')

(4) NOR Function design with McCulloch-Pitts model


Step 1: Generate a vector of inputs and a vector ou weights
# matrix of inputs
input_table = np.array([
[0,0], # both no
[0,1], # one no, one yes
[1,0], # one yes, one no
[1,1] # bot yes
])
print(f'input table:\n{input_table}')
# array of weights
weights = np.array([-1,-1])
print(f'weights: {weights}')

Step 2: Compute the dot products between the matrix of inputs and weights
# dot product matrix of inputs and weights
dot_products = input_table @ weights
print(f'Dot products: {dot_products}')
Step 3: Define the threshold activation function
def linear_threshold_gate(dot: int, T: float) -> int:
'''Returns the binary threshold output'''
if dot >= T:
return 1
else:
return 0

Step 4: Compute the output based on the threshold


T = 0
for i in range(0,4):
activation = linear_threshold_gate(dot_products[i], T)
print(f'Activation: {activation}')

Design and Implementation of Perceptron to


detect misclassification rate in Iris Dataset
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def load_data():
URL_='https://archive.ics.uci.edu/ml/machine-learning-
databases/iris/iris.data'
data = pd.read_csv(URL_, header = None)
print(data)
# make the dataset linearly separable
data = data[:100]
data[4] = np.where(data.iloc[:, -1]=='Iris-setosa', 0, 1)
data = np.asmatrix(data, dtype = 'float64')
return data
data = load_data()
plt.scatter(np.array(data[:50,0]), np.array(data[:50,2]), marker='o',
label='setosa')
plt.scatter(np.array(data[50:,0]), np.array(data[50:,2]), marker='x',
label='versicolor')
plt.xlabel('petal length')
plt.ylabel('sepal length')
plt.legend()
plt.show()
def perceptron(data, num_iter):
features = data[:, :-1]
labels = data[:, -1]
# set weights to zero
w = np.zeros(shape=(1, features.shape[1]+1))
misclassified_ = []
for epoch in range(num_iter):
misclassified = 0
for x, label in zip(features, labels):
x = np.insert(x,0,1)
y = np.dot(w, x.transpose())
target = 1.0 if (y > 0) else 0.0
delta = (label.item(0,0) - target)
if(delta): # misclassified
misclassified += 1
w += (delta * x)
misclassified_.append(misclassified)
return (w, misclassified_)
num_iter = 10
w, misclassified_ = perceptron(data, num_iter)

Name: Implementation of De-Morgan’s Law


Aim:
To write a Program in MATLAB to implement De-Morgan’s law.
Algorithm:
1. Read the membership values of two fuzzy set.
2. Perform Union operation by using max() function and take the complement
for the fuzzy set.
3. Perform Intersection operation by using min() function and take the complement.
4. Perform Complement operation for the both fuzzy sets.
5. Perform Intersection operation and Union operation for the Complements of fuzzy
set.
6. Verify the formula and display the result.
Program:
% Enter the membership values of fuzzy set
u = input (‘Enter the membership values of first fuzzy set’);
v = input (‘Enter the membership values of second fuzzy set’);
%To perform
operation
w=max (u, v);
p=min (u, v);
q1=1-u;
q2=1-v;
x1=1-w;
x2=min(q1,2);
y1=1
p;
y2=max(q1-q2);
%Display Output
disp(‘Union of two fuzzy sets ’);
disp(w);
disp(‘Intersection of two fuzzy sets ’); disp(p);
disp(‘Complement of first fuzzy set ’); disp(q1);
disp(‘Complement of second fuzzy set ’); disp(q2);
disp(‘De-Morgan’s Law’);
disp(‘LHS’); disp(x1); disp(‘RHS’); disp(x2); disp(LHS); disp(y1); disp(‘RHS’);
disp(y2);

Sample Input and output:

Enter the membership values of first fuzzy set [0.3


0.4] Enter the membership values of second fuzzy
set [0.2 0.5] Union of two fuzzy sets
0.3000. 0.5000
Intersection of two
fuzzy sets 0.3000
0.4000.
Complement of first
fuzzy set 0.7000
0.6000.
Complement of second fuzzy set
0.8000 0.5000.
De-Morgan’s Law: (i) (A ∪ B)' = A' ∩ B' and (ii) (A ∩ B)' = A'
∪ B'
Output: (0.3 0.5)’ = (0.7 0.6) ∩ (0.8 0.5) = (0.7 0.5)

Discussion:
Thus, the MATLAB program for implementation of De-Morgan’s has been
executed successfully and the output is verified.

You might also like