CCS364 – SOFT COMPUTING
RECORD NOTE BOOK – 25’
REGISTER NUMBER
NAME:
BRANCH: INFORMATION TECHNOLOGY
GOVERNMENT COLLEGE OF ENGINEERING,
ERODE – 638316
RECORD NOTEBOOK
Reg. No.
Certified that this is the bonafide record of work done by
Selvan/Selvi of the SIXTH semester B. TECH
INFORMATION TECHNOLOGY branch during the Academic year 2024-2025
in the CCS364 – SOFT COMPUTING LABORATORY.
Staff-in-charge Head of the Department
Submitted for the University Practical Examination held on __________________
at the Government College of Engineering, Erode.
INTERNAL EXAMINER EXTERNAL EXAMINER
INDEX
S.NO DATE TITLE OF THE EXPERIMENT PAGE SIGNATURE
NO
1 Fuzzy control/inference system 1
2 Classification with a discrete 5
perception
3 XOR with backpropagation 9
algorithm
4 Self-Organizing maps for a specific
13
application
5 Maximizing a function using Genetic
17
algorithm
6 Implementation of two input sine
21
function
7 Implementation of three input sine
24
function
Ex.no: 1
Implementation of fuzzy control/ inference
Date:
system.
AIM:
To implement a fuzzy inference system for decision-making based on fuzzy logic
principles.
PROCEDURE:
1. Define input and output variables with appropriate linguistic terms.
2. Assign membership functions to each fuzzy set.
3. Create a rule base using IF-THEN statements based on expert knowledge.
4. Apply fuzzification and inference to process input through the rule base.
5. Defuzzify the output to obtain a crisp decision or control action.
PROGRAM:
import numpy as np
import skfuzzy as fuzzy
import matplotlib.pyplot as plt
# Define the universe of discourse for temperature and fan speed
temp_range = np.arange(0, 41, 1) # Temperature range from 0 to 40 degrees
Celsius
fan_speed_range = np.arange(0, 101, 1) # Fan speed range from 0 to 100%
# Define fuzzy membership functions for temperature
temp_low = fuzz.trimf(temp_range, [0, 0, 20])
temp_medium = fuzz.trimf(temp_range, [0, 20, 40])
temp_high = fuzz.trimf(temp_range, [20, 40, 40])
1
# Define fuzzy membership functions for fan speed
fan_low = fuzz.trimf(fan_speed_range, [0, 0, 50])
fan_medium = fuzz.trimf(fan_speed_range, [0, 50, 100])
fan_high = fuzz.trimf(fan_speed_range, [50, 100, 100])
# Visualize the fuzzy sets
plt.figure(figsize=(10, 5))
# Temperature Membership Functions
plt.subplot(1, 2, 1)
plt.plot(temp_range, temp_low, label='Low Temperature')
plt.plot(temp_range, temp_medium, label='Medium Temperature')
plt.plot(temp_range, temp_high, label='High Temperature')
plt.title('Temperature Membership Functions')
plt.xlabel('Temperature (°C)')
plt.ylabel('Membership Degree')
plt.legend()
# Fan Speed Membership Functions
plt.subplot(1, 2, 2)
plt.plot(fan_speed_range, fan_low, label='Low Fan Speed')
plt.plot(fan_speed_range, fan_medium, label='Medium Fan Speed')
plt.plot(fan_speed_range, fan_high, label='High Fan Speed')
plt.title('Fan Speed Membership Functions')
plt.xlabel('Fan Speed (%)')
plt.ylabel('Membership Degree')
2
plt.legend()
plt.tight_layout()
plt.show()
# Fuzzy rule evaluation (Fuzzy inference)
# Example input: temperature is 25°C
temp_input = 25
# Calculate the membership values for the input
temp_low_level = fuzz.interp_membership(temp_range, temp_low, temp_input)
temp_medium_level = fuzz.interp_membership(temp_range, temp_medium,
temp_input)
temp_high_level = fuzz.interp_membership(temp_range, temp_high,
temp_input)
# Apply fuzzy rules to determine fan speed membership functions
fan_activation_low = np.fmin(temp_low_level, fan_low) # If temperature is
low, fan speed is low
fan_activation_medium = np.fmin(temp_medium_level, fan_medium) # If
temperature is medium, fan speed is medium
fan_activation_high = np.fmin(temp_high_level, fan_high) # If temperature is
high, fan speed is high
# Aggregate the fuzzy outputs
aggregated_fan_speed = np.fmax(fan_activation_low,
np.fmax(fan_activation_medium, fan_activation_high))
# Defuzzification (Centroid method)
fan_speed_output = fuzz.defuzz(fan_speed_range, aggregated_fan_speed,
'centroid')
3
# Display the results
print(f"Input Temperature: {temp_input}°C")
print(f"Defuzzified Fan Speed: {fan_speed_output:.2f}%").
OUTPUT:
RESULT:
The fuzzy inference system was successfully implemented, providing
accurate and logical outputs based on the defined fuzzy rules and input
conditions.
4
Ex.no: 2
Programming exercise on classification with
A discrete perceptron
Date:
AIM:
To implement a discrete perceptron algorithm to classify data points into two classes
using supervised learning.
PROCEDURE:
1. Initialize parameters:
Set initial weights and bias to 0 or small random values.
Define the learning rate (usually 1 for discrete perceptron).
2. Input the dataset:
Prepare a small set of labeled data points (e.g., 2D features with class labels -1
or +1).
3. Training process:
For each data point, compute the weighted sum:
output = sign(w·x + b)
where sign() returns +1 or -1.
If the prediction is wrong, update weights and bias:
w = w + learning_rate * (target - prediction) * x
b = b + learning_rate * (target - prediction)
4. Repeat steps:
Continue iterating through the dataset until all points are classified correctly (or
max iter ations reached).
5
5. Test the perceptron:
Use trained weights and bias to classify new test points.
PROGRAM:
import numpy as np
class Perceptron:
def init (self, input_size):
self.weights = np.zeros(input_size)
self.bias = 0
def predict(self, inputs):
activation = np.dot(self.weights, inputs) + self.bias
return 1 if activation > 0 else 0
def train(self, inputs, targets, learning_rate=0.1, epochs=100):
for _ in range(epochs):
for x, y in zip(inputs, targets):
prediction = self.predict(x)
error = y - prediction
self.weights += learning_rate * error * x
self.bias += learning_rate * error
def main():
# Define input data for two classes
class_0 = np.array([[1, 1], [2, 1], [1, 2]])
class_1 = np.array([[4, 5], [5, 6], [6, 5]])
6
# Combine and label data (0 for class_0, 1 for class_1)
inputs = np.vstack((class_0, class_1))
targets = np.array([0, 0, 0, 1, 1, 1])
# Create perceptron
perceptron = Perceptron(input_size=2)
# Train perceptron
perceptron.train(inputs, targets, learning_rate=0.1, epochs=50)
# Test the perceptron with new data
test_data = np.array([[3, 3], [1, 0], [6, 7]])
print("Testing trained perceptron:")
for data in test_data:
prediction = perceptron.predict(data)
print(f"Input: {data}, Predicted class: {prediction}")
if name == " main ":
main()
7
OUTPUT:
RESULT:
Thus the experiment is successfully written and demonstrated.
8
Ex.no: 3
Implementation of XOR with backpropagation
Date: algorithm
AIM:
To implement the XOR logic gate using a neural network trained with
the Backpropagation algorithm.
ALGORITHM:
1. Initialize the Network:
Create a neural network with 2 input neurons, 1 hidden layer
(with 2 neurons), and 1 output neuron.
Initialize weights and biases with small random values.
2. Feedforward Pass:
Compute activations of the hidden layer using the input and
weights.
Apply an activation function (commonly sigmoid) to the
hidden layer.
Compute the output layer's activation using the hidden layer's
output.
3. Calculate Error:
Compare the predicted output with the actual XOR output
and compute the error.
4. Backpropagation:
Calculate gradients of error with respect to output, hidden
weights, and biases.
Update weights and biases using gradient descent.
5. Training Loop:
Repeat feedforward and backpropagation for several
epochs until the error is minimized.
9
PROGRAM :
import numpy as np
# Sigmoid activation function and its derivative
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1 - x)
# input and output for XOR logic gate
input_data = np.array([[0, 0],
[0, 1],
[1, 0],
[1, 1]])
target_output = np.array([[0],
[1],
[1],
[0]])
# Neural network architecture
input_size = 2
hidden_size = 2
output_size = 1
learning_rate = 0.5
epochs = 10000
# Initialize weights and biases
np.random.seed(42)
hidden_weights = np.random.uniform(size=(input_size, hidden_size))
hidden_bias = np.random.uniform(size=(1, hidden_size))
output_weights = np.random.uniform(size=(hidden_size, output_size))
output_bias = np.random.uniform(size=(1, output_size))
10
# Training the network
for _ in range(epochs):
# Forward pass
hidden_layer_input = np.dot(input_data, hidden_weights) + hidden_bias
hidden_layer_output = sigmoid(hidden_layer_input)
final_input = np.dot(hidden_layer_output, output_weights) + output_bias
predicted_output = sigmoid(final_input)
# Calculate error
error = target_output - predicted_output
# Backpropagation
d_predicted_output = error * sigmoid_derivative(predicted_output)
error_hidden_layer = d_predicted_output.dot(output_weights.T)
d_hidden_layer = error_hidden_layer *
sigmoid_derivative(hidden_layer_output)
# Update weights and biases
output_weights += hidden_layer_output.T.dot(d_predicted_output) *
learning_rate
output_bias += np.sum(d_predicted_output, axis=0, keepdims=True) *
learning_rate
hidden_weights += input_data.T.dot(d_hidden_layer) * learning_rate
hidden_bias += np.sum(d_hidden_layer, axis=0, keepdims=True) *
learning_rate
# Test the network
print("Final predictions after training:")
for i in range(len(input_data)):
print(f"Input: {input_data[i]} => Predicted:
{predicted_output[i][0]:.4f}")
11
OUTPUT:
RESULT:
The XOR function was successfully implemented using a neural
network with the Backpropagation algorithm.
12
Ex.no: 4
Implementation of self- organizing
maps for a specific application
Date:
AIM:
To implement a Self-Organizing Map(SOM) using Python in Google colab to
perform on a specific application.
PREREQUISITES:
Platform: Google colab
Libraries:
Numpy
Pandas
Matplotlib
Sklearn.preprocessing
Minisom
ALGORITHM:
1. Data Loading: Read Mall_Customers.csv.
2. Preprocessing: Extract features (Age, Annual Income, Spending
Score) and apply Min‑Max scaling.
3. SOM Initialization: Create a 10×10 SOM with specified sigma and
learning rate.
4. Training: Train the SOM for 100 iterations.
5. Visualization: Plot the U‑Matrix and overlay data points.
6. Cluster Mapping: Assign each customer to its Best‑Matching Unit
(BMU).
7. Profiling: Compute cluster counts and mean feature values per
cluster.
13
8. Interpretation: Analyze clusters for insights.
CODE:
# Step 1: Install and import libraries
!pip install minisom
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from minisom import MiniSom
from sklearn.preprocessing import MinMaxScaler
# Step 2: Load data
df = pd.read_csv('Mall_Customers.csv')
# Step 3: Preprocess data
X = df.iloc[:, [2, 3, 4]].values # Age, Income, Spending Score
scaler = MinMaxScaler()
X_scaled = scaler.fit_transform(X)
# Step 4: Initialize and train SOM
som = MiniSom(x=10, y=10, input_len=3, sigma=1.0,
learning_rate=0.5)
som.random_weights_init(X_scaled)
som.train_random(data=X_scaled, num_iteration=100)
# Step 5: Visualize U-Matrix
from pylab import bone, pcolor, colorbar, plot
bone()
pcolor(som.distance_map().T) colorbar()
14
for x in X_scaled:
w = som.winner(x)
plot(w[0]+0.5, w[1]+0.5, 'o', markerfacecolor='None',
markeredgecolor='r', markersize=8)
plt.title('SOM Customer Segmentation')
plt.show()
# Step 6: Save figure
plt.savefig('/content/som_result.png')
# Step 7: Map BMUs and profile clusters
bmus = np.array([som.winner(x) for x in X_scaled])
cluster_ids = [f"{w[0]}_{w[1]}" for w in bmus]
df['cluster'] = cluster_ids
cluster_counts = df['cluster'].value_counts().sort_index()
cluster_profile = df.groupby('cluster').agg({
'Age': 'mean',
'Annual Income (k$)': 'mean',
'Spending Score (1-100)': 'mean',
'CustomerID': 'count'
}).rename(columns={'CustomerID': 'Count'})
15
OUTPUT:
RESULT:
The Self-Organizing Map was successfilly implemented and
customer segments were identified.
16
Ex.no: 5 Programming exercises on maximizing a
function using Genetic algorithm.
Date:
AIM:
To implement a Genetic Algorithm (GA) in Python for maximizing the
mathematical function:
f(x) = x . sin(10 π x) + 1 where x ∈ [0,1]
PROCEDURE:
1. Define the fitness function: Represents the objective to be maximized.
2. Encode individuals: Use binary strings to represent real numbers
(chromosomes).
3. Initialize population: Randomly generate chromosomes.
4. Evaluate fitness: Convert binary to decimal and evaluate f(x).
5. Selection: Choose parents based on fitness (tournament selection).
6. Crossover: Combine two parents using single-point crossover.
7. Mutation: Flip bits in chromosomes at random positions with a small
mutation rate.
8. Repeat: Create new generations and update the population.
9. Track: Record best and average fitness for plotting.
10. Output: Display best solution and plot fitness over generations.
PROGRAM:
import random
import math
import matplotlib.pyplot as plt
17
# Fitness function
def fitness(x):
return x * math.sin(10 * math.pi * x) + 1
# Decode binary to float in [0, 1]
def decode(binary_str, length=16):
max_int = 2**length - 1
integer = int(binary_str, 2)
return integer / max_int
# Initialize population
def init_population(size, length):
return [''.join(random.choice('01') for _ in range(length)) for _ in range(size)]
# Tournament selection
def select(pop, scores, k=3):
selected = random.choices(list(zip(pop, scores)), k=k)
return max(selected, key=lambda x: x[1])[0]
# Crossover
def crossover(p1, p2, rate=0.8):
if random.random() < rate:
point = random.randint(1, len(p1) - 1)
return p1[:point] + p2[point:], p2[:point] + p1[point:]
return p1, p2
# Mutation
def mutate(chrom, rate=0.01):
return ''.join(bit if random.random() > rate else '1' if bit == '0' else '0' for bit in
chrom)
# Genetic Algorithm
def genetic_algorithm(pop_size=50, length=16, gens=100, crossover_rate=0.8,
mutation_rate=0.01):
population = init_population(pop_size, length)
best_score = -1
best_chrom = ""
best_fitness_history = []
18
average_fitness_history = []
for generation in range(gens):
decoded = [decode(c, length) for c in population]
scores = [fitness(x) for x in decoded]
# Track best and average
avg = sum(scores) / len(scores)
best_idx = scores.index(max(scores))
best_fitness_history.append(scores[best_idx])
average_fitness_history.append(avg)
if scores[best_idx] > best_score:
best_score = scores[best_idx]
best_chrom = population[best_idx]
# Generate new population
new_pop = []
while len(new_pop) < pop_size:
p1 = select(population, scores)
p2 = select(population, scores)
c1, c2 = crossover(p1, p2, crossover_rate)
new_pop.extend([mutate(c1, mutation_rate), mutate(c2,
mutation_rate)])
population = new_pop[:pop_size]
# Optional print
print(f"Generation {generation+1}: Best Fitness = {scores[best_idx]:.5f},
x = {decode(population[best_idx]):.5f}")
# Final best result
best_x = decode(best_chrom, length)
return best_x, best_score, best_fitness_history, average_fitness_history
# Run the GA and Output
best_x, best_fit, best_history, avg_history = genetic_algorithm()
print(f"\nBest x = {best_x:.5f}, Best f(x) = {best_fit:.5f}")
# Plot
19
plt.figure(figsize=(10, 5))
plt.plot(best_history, label='Best Fitness')
plt.plot(avg_history, label='Average Fitness')
plt.title('Fitness Over Generations')
plt.xlabel('Generation')
plt.ylabel('Fitness')
plt.legend()
plt.grid(True)
plt.show()
OUTPUT:
Python genalgorithm.py
RESULT:
Thus the Maximizing a function using Genetic algorithm was written and
implemented successfully.
20
Ex.no: 6
Implementation of two input sine function
Date:
AIM:
To implement a Python program that computes and visualizes the sine of the
two input.
PROCEDURE:
1. Start the program and import the math module
Import the built-in math library to access trigonometric
functions and conversions.
2. Prompt the user to input two angle values
Take two numerical inputs from the user in degrees using the
input() function.
3. Convert the input angles from degrees to radians
Use math.radians() to convert each degree value to radians, as
the math.sin() function requires angles in radians.
4. Calculate the sine of each angle
Use a=math.sin() to compute the sine of both converted
angles(in radians).
5. Perform additional sine-based computations
Calculate the sum of the sine values: sin(x) + sin(y)
Calculate the sine of the sum of angles: sin(x + y)
21
6. Display the results
Use print() statements to show the values of sin(x), sin(y),
sin(x) + sin(y) and sin(x+y) clearly.
7. End of the program
Ensure the program exits cleanly after displaying all required
outputs.
PROGRAM:
import math
# Take two inputs from the user in degrees
x_deg = float(input("Enter first angle (in degrees): "))
y_deg = float(input("Enter second angle (in degrees): "))
# Convert degrees to radians
x_rad = math.radians(x_deg)
y_rad = math.radians(y_deg)
# Compute sine values
sin_x = math.sin(x_rad)
sin_y = math.sin(y_rad)
# Combined sine computations
sin_sum = sin_x + sin_y
sin_xy = math.sin(x_rad + y_rad)
# Display results
print(f"sin({x_deg}) = {sin_x:.4f}")
print(f"sin({y_deg}) = {sin_y:.4f}")
print(f"sin({x_deg}) + sin({y_deg}) = {sin_sum:.4f}")
print(f"sin({x_deg} + {y_deg}) = sin({x_deg + y_deg}) = {sin_xy:.4f}")
22
OUTPUT:
RESULT:
Thus the program were successfully implemented using the math library.
23
Ex.no: 7
Implementation of three input non-linear
Date: function
AIM:
To implement three input non-linear function using a sigmoid activation.
PROCEDURE:
Step 1: Define the mathematical structure of the non-linear function.
Identify the non-linear function you want to implement.
For example, let’s consider a function of the form:
f(x,y,z) = a⋅x2+b⋅y3+sin(z)
The function is non-linear because it involves powers (quadratic and cubic
terms) and a trigonometric operation.
Step 2: Set up the necessary environment and dependencies.
Ensure you have the necessary Python libraries to handle the math and any
additional functionality. For a non-linear function, you would often use NumPy
for efficient computation.
>pip install numpy
Step 3: Implement the non-linear function code.
Implement the non-linear function by taking three input parameters and
performing the necessary mathematical operations.
Step 4: Test the function with different inputs.
Step 5: Handle any edge cases and exceptions.
Handle edge cases for inputs such as zero values, negative values, or values
that might lead to mathematical exceptions (like taking the sine of a large
number).
24
Step 6: Optionally visualize the function's behavior.
Visualize how the function behaves with different inputs, you can plot the
output for a range of values.
Step 7: Optimize for performance if needed.
Step 8: Deploy for broader use if necessary.
PROGRAM:
import numpy as np
# Sigmoid activation function
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# Nonlinear function with three inputs
def nonlinear_function(x1, x2, x3):
# Assign weights (can be adjusted)
w1 = 0.6
w2 = -1.0
w3 = 0.8
bias = 0.2
# Weighted sum
net_input = w1 * x1 + w2 * x2 + w3 * x3 + bias
# Apply nonlinear activation
output = sigmoid(net_input)
return output
# Main block for user input and result
if _name_ == "_main_":
print("Three-Input Nonlinear Function using Sigmoid Activation")
# Get inputs from user
x1 = float(input("Enter input x1: "))
25
x2 = float(input("Enter input x2: "))
x3 = float(input("Enter input x3: "))
# Compute output
result = nonlinear_function(x1, x2, x3)
# Display result
print(f"Nonlinear function output: {result:.4f}")
OUTPUT:
>python threeipfn.py
RESULT:
Thus the program were written and executed successfully.
26
27