Soft Computing File-2 2
Soft Computing File-2 2
0 0 0
0 1 0
1 0 0
1 1 1
# Perceptron class
class Perceptron: def __init__(self, input_size,
learning_rate=0.1):
self.weights = np.zeros(input_size) # Initialize weights to zero
self.bias = 0 # Initialize bias
self.learning_rate = learning_rate # Learning rate
1. Initialization: The MADALINE class initializes the weights and learning rate.
3. Prediction: The predict method computes the output based on the current
weights.
4. Training: The train method updates the weights based on the difference between
the predicted and actual outputs.
5. Training Data: The training data for the NOR gate is defined in bipolar format.
6. Testing: After training, the network is tested against the same inputs to see if it
correctly predicts the NOR outputs.
import numpy as np
class MADALINE: def __init__(self, input_size,
learning_rate=0.1):
self.weights = np.random.rand(input_size) * 0.1 # Small random weights
self.learning_rate = learning_rate
OUTPUT:
Input: [-1 -1], Predicted Output: 1
Input: [-1 1], Predicted Output: -1
Input: [ 1 -1], Predicted Output: -1
Input: [ 1 1], Predicted Output: -1
# Perceptron prediction
def predict(self, inputs):
# Weighted sum + bias
summation = np.dot(inputs, self.weights) + self.bias
return bipolar_step_function(summation)
# Train the second layer (using the first layer outputs as inputs)
layer1_outputs = np.array([perceptron.predict(inputs) for perceptron in
self.layer1] for inputs in training_inputs)
self.layer2.train(layer1_outputs, labels, epochs)
3. Prediction: The predict method computes the output based on the current
weights, including the bias term.
4. Training: The train method continues to update the weights until no changes are
needed (i.e., the predictions match the target labels).
5. Training Data: The training data for the AND gate is defined, along with the
corresponding labels.
import numpy as np
OUTPUT:
Final weights after training: [0.2, 0.2, 0.2]
1. Forward propagation:
o Compute the weighted sum of inputs for the neuron.
o Apply the activation function to get the output.
2. Error calculation:
o The error is the difference between the target output and the actual
output of the neuron.
3. Backpropagation:
o Compute the gradient of the error with respect to the weights using the
chain rule.
o Update the weights using the formula: w=w−α ∂E∂ww = w - \alpha \cdot
\frac{\partial E}{\partial w}w=w−α ∂w∂E where EEE is the error and
α\alphaα is the learning rate.
Python Code Implementation:
import numpy as np
# Given data
inputs = np.array([0, 1]) # Input pattern [0, 1] target
= 1 # Target output
1. FuzzySet Class: This class represents a fuzzy set, which includes methods for
union, intersection, and complement operations.
3. Union Method: Computes the union of two fuzzy sets by taking the maximum
membership value for each element.
4. Intersection Method: Computes the intersection of two fuzzy sets by taking the
minimum membership value for each element.
import numpy as np
class FuzzySet: def __init__(self, elements,
membership_values): self.elements = elements
self.membership_values = membership_values
def complement(self):
"""Perform complement operation on the fuzzy set."""
complement_membership = [1 - value for value in self.membership_values]
return FuzzySet(self.elements, complement_membership)
def __str__(self):
"""String representation of the fuzzy set.""" return f"Elements:
{self.elements}\nMembership Values: {self.membership_values}"
OUTPUT
Fuzzy Set A:
Elements: ['x1', 'x2', 'x3', 'x4']
Membership Values: [0.2, 0.5, 0.8, 0.1]
Fuzzy Set B:
Elements: ['x1', 'x2', 'x3', 'x4']
Membership Values: [0.6, 0.3, 0.4, 0.9]
Union of A and B:
ANS 7. To create a program that asks the user to enter two fuzzy sets and computes
the resultant fuzzy relation, we will follow these steps:
1. Input Fuzzy Sets: Ask the user to enter two fuzzy sets. These sets can be
represented as lists of membership values.
2. Compute Fuzzy Relation: Create a fuzzy relation based on the two sets. We will
limit the relation to values that are greater than 6.
3. filter_relation: This function filters the fuzzy relation to include only those entries
where the membership value is greater than 6.
4. main: This function orchestrates the input, computation, and output of the fuzzy
relation.
Example Usage:
When you run the program, it will prompt you to enter two fuzzy sets. For example:
Enter the fuzzy set A (comma-separated values): 5.5, 7.2, 8.1
Enter the fuzzy set B (comma-separated values): 6.1, 4.3, 9.0 Resultant
Fuzzy Relation (values greater than 6):
Relation (7.2, 6.1): 6.10
Relation (7.2, 9.0): 7.20
Relation (8.1, 6.1): 6.10
Relation (8.1, 9.0): 8.10
Note:
• The program assumes that the user will enter valid numeric values. If the values
are not numeric or not in the correct format, it will prompt the user to enter the
values again.
The filtering condition for "greater than 6" is applied to the resultant fuzzy relation,
which is based on the minimum of the corresponding membership values from the two
fuzzy sets. Adjust this logic based on your specific needs.
import numpy as np
for i in range(rows_A):
for j in range(cols_B):
C[i][j] = np.max(np.minimum(A[i, :], B[:, j]))
return C
C = np.zeros((rows_A, cols_B))
for i in range(rows_A):
for j in range(cols_B):
C[i][j] = np.max(A[i, :] * B[:, j])
return C
# Compute compositions
C_max_min = max_min_composition(A, B)
C_max_product = max_product_composition(A, B)
# Output results print("Fuzzy
Relation A (3x3):") print(A)
print("\nFuzzy Relation B
(3x4):") print(B)
print("\nMax-Min Composition of A and B:")
print(C_max_min) print("\nMax-Product
Composition of A and B:")
print(C_max_product)
OUTPUT
Fuzzy Relation A (3x3):
[[0.5488135 0.71518937 0.60276338]
[0.54488318 0.4236548 0.64589411]
[0.43758721 0.891773 0.96366276]]
Fuzzy Relation B (3x4):
[[0.38344152 0.79172504 0.52889492 0.56804456]
[0.92559664 0.07103606 0.0871293 0]
ANS 9 . To create two random fuzzy sets and then compute the fuzzy relation indexed
by the Cartesian product of those sets, we can follow these steps:
1. Define the dimensions: Let the user define the dimensions ( N ) and ( M ) for the
two fuzzy sets.
2. Generate random fuzzy sets: Create two random fuzzy sets of dimensions ( N )
and ( M ) with membership values between 0 and 1.
3. Compute the Cartesian product: Generate the Cartesian product of the two fuzzy
sets.
4. Create the fuzzy relation: Use the membership values from the two fuzzy sets to
create a fuzzy relation.
Here's the Python code to implement
this: Python CODE import numpy as np
def create_random_fuzzy_set(size):
"""Create a random fuzzy set of given size with values between 0 and
1.""" return np.random.rand(size) def cartesian_product(set_a, set_b):
"""Compute the Cartesian product of two sets.""" def
fuzzy_relation(set_a, set_b):
"""Create a fuzzy relation based on the Cartesian product of two fuzzy
sets.""" relation = {} for i, a in enumerate(set_a): for j, b in enumerate(set_b):
relation[(a, b)] = min(set_a[i], set_b[j]) # Using min for fuzzy
relation return relation def main():
#User input for dimensions
N = int(input("Enter the dimension N for the first fuzzy set: "))
M = int(input("Enter the dimension M for the second fuzzy set: "))
# Create random fuzzy sets
fuzzy_set_a = create_random_fuzzy_set(N)
fuzzy_set_b = create_random_fuzzy_set(M)
print("\nFuzzy Set A (Dimension N):")
print(fuzzy_set_a)
print("\nFuzzy Set B (Dimension M):")
print(fuzzy_set_b)
# Compute the Cartesian product
cartesian_prod = cartesian_product(fuzzy_set_a,
fuzzy_set_b) print("\nCartesian Product of Fuzzy Set A and
B:") print(cartesian_prod) # Create fuzzy relation
relation = fuzzy_relation(fuzzy_set_a, fuzzy_set_b)
print("\nFuzzy Relation (Indexed by Cartesian
Product):") for key, value in relation.items():
print(f"Relation {key}: {value:.2f}") if __name__ ==
"__main__":
main()
Explanation:
4. main: This function orchestrates user input, generates the fuzzy sets, computes
the Cartesian product, and creates the fuzzy relation.
How to Run the Program:
3. The program will display the generated fuzzy sets, the Cartesian product, and the
fuzzy relation.
Example Output:
Enter the dimension N for the first fuzzy set: 3 Enter
the dimension M for the second fuzzy set: 2 Fuzzy
Set A (Dimension N):
[0.34 0.56 0.78]
Fuzzy Set B (Dimension M):
[0.12 0.89]
Cartesian Product of Fuzzy Set A and B:
[(0.34, 0.12), (0.34, 0.89), (0.56, 0.12), (0.56, 0.89), (0.78, 0.12), (0.78, 0.89)] Fuzzy
Relation (Indexed by Cartesian Product):
Relation (0.34, 0.12): 0.12 Relation
(0.34, 0.89): 0.34
Relation (0.56, 0.12): 0.12
Relation (0.56, 0.89): 0.56
Relation (0.78, 0.12): 0.12
Relation (0.78, 0.89): 0.78
This output will vary each time you run the program due to the random generation of
the fuzzy sets.
1. Fuzzy Rule Creation: We will create a simple fuzzy rule-based system that uses
fuzzy sets and rules.
2. Genetic Algorithm: The genetic algorithm will optimize the parameters of the
fuzzy rules.
def select_parents(self):
fitness_scores = [self.fitness(chromosome) for chromosome in self.population]
selected_indices = np.random.choice(range(self.population_size), size=2,
p=fitness_scores/np.sum(fitness_scores))
return [self.population[i] for i in selected_indices]
def crossover(self, parent1, parent2):
crossover_point = random.randint(1, len(parent1) - 1)
return parent1[:crossover_point] + parent2[crossover_point:]
def mutate(self, chromosome): for i in
range(len(chromosome)): if random.random() <
self.mutation_rate: chromosome[i] = random.uniform(0,
1) return chromosome def run(self, rules, inputs,
expected_outputs):
self.initialize_population(len(rules))
for generation in range(self.generations):
new_population = [] for _ in
range(self.population_size):
parent1, parent2 = self.select_parents()
child = self.crossover(parent1, parent2) child
= self.mutate(child)
new_population.append(child) self.population
= new_population
best_chromosome = max(self.population, key=lambda c: self.fitness(c, rules, inputs,
expected_outputs)) return best_chromosome
# Example usage if
__name__ == "__main__":
# Define fuzzy sets low = FuzzySet("Low", lambda x: max(0, min(1,
(1 - x))) medium = FuzzySet("Medium", lambda x: max(0, min(1, (x -
0.5) * 2)) high = FuzzySet("High", lambda x: max(0, min(1, (x - 1)))
# Define fuzzy rules
rules = [
FuzzyRule([low], 0), # If Low then Output is 0
Implementation in Python:
# Define the sets
P = {'P1', 'P2', 'P3', 'P4', 'P5'} # Plant varieties
D = {'D1', 'D2', 'D3', 'D4', 'D5'} # Diseases
S = {'S1', 'S2', 'S3', 'S4', 'S5'} # Symptoms
ANS. To train an autocorrector using the specified patterns with a McCulloch-Pitts neural
network, you would typically follow these steps:
1. Define the Patterns: You have three training patterns (a1, a2, a3) and three test patterns
(ax, ay, az).
2. Set Up the McCulloch-Pitts Neuron: Create a neuron model that can learn from the
training patterns.
3. Train the Neuron: Use the training patterns to adjust the weights of the neuron.
4. Test the Neuron: Evaluate the neuron with the test patterns to see how well it predicts
or corrects them.
Here’s a Python implementation of this process:
python import numpy as np class
McCullochPittsNeuron: def __init__(self,
weights, threshold):
self.weights = weights self.threshold = threshold def activate(self,
inputs):S # Calculate the weighted sum weighted_sum =
np.dot(self.weights, inputs) # Apply the step function (activation
function) return 1 if weighted_sum >= self.threshold else -1 def
train(self, training_data, learning_rate=1): for inputs in training_data:
output = self.activate(inputs[:-1]) # Last element is the expected output
error = inputs[-1] – output
# Test cases
test_missing = np.array([1, 0, 1, 1]) # One missing entry
test_mistake = np.array([1, -1, -1, 1]) # One mistake
W, recovered_missing, recovered_mistake
MATLAB Code:
or_not = ~A | ~B;
% Display results
% Display results
Here's how to implement a simple McCulloch-Pitts neural network to simulate the AND-NOT function in
Python:
We'll create a class for the McCulloch-Pitts neuron that will take inputs and weights, and produce an
output based on a threshold.
The weights and threshold will be set such that the neuron outputs the desired AND-NOT logic.
IN PYTHON
VerifyOpen In EditorEditCopy code
class McCullochPittsNeuron:
self.weights = weights
inputs))
and_not_function(inputs):
output = and_not_function(inputs)
Explanation:
• The McCullochPittsNeuron class defines the neuron model with weights and a threshold.
• The activate method computes the weighted sum of inputs and checks if it meets the threshold
to produce an output.
• The and_not_function function initializes the neuron with appropriate weights and threshold
values to simulate the AND-NOT logic.
• We then test the function with all possible combinations of binary inputs.
Output:
When you run the code, you should see the outputs corresponding to the AND-NOT logic:
This confirms that the McCulloch-Pitts neuron is correctly implementing the AND-NOT function.