0% found this document useful (0 votes)
19 views12 pages

Soft Computing Lab Manual

Uploaded by

india.tech2106
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)
19 views12 pages

Soft Computing Lab Manual

Uploaded by

india.tech2106
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/ 12

Submitted By Submitted To

Name : Bhanu Pratap Singh Mrs.Anupam Yadav


Sec : i2
Roll No. : 2215990019
Artificial Neural Network (ANN)
Objective

Small Image Classification Using Convolutional Neural Network (CNN)

Solution
Bayesian Neural Network (BNN)

Objective

To demonstrate uncertainty estimation in predictions using a Bayesian Neural Network (BNN).

Solution

Code Implementation (BNN Example with TensorFlow Probability):

import tensorflow as tf

import tensorflow_probability as tfp

import numpy as np

# XOR dataset

X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=np.float32)

y = np.array([[0], [1], [1], [0]], dtype=np.float32)

# Bayesian layer

tfd = tfp.distributions

model = tf.keras.Sequential([

tfp.layers.DenseVariational(4, input_shape=(2,),

make_prior_fn=lambda t: tfd.Normal(loc=0., scale=1.),

make_posterior_fn=lambda t: tfd.Normal(loc=tf.Variable(tf.zeros_like(t)),
scale=tf.nn.softplus(tf.Variable(tf.zeros_like(t))))),

tf.keras.layers.Dense(1, activation='sigmoid')

])

# Compile and train the model

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])


model.fit(X, y, epochs=500, verbose=0)

# Predict with uncertainty estimation

predictions = [model(X, training=True) for _ in range(1000)]

pred_mean = tf.reduce_mean(predictions, axis=0)

pred_stddev = tf.math.reduce_std(predictions, axis=0)

print("Mean Predictions:", pred_mean.numpy().flatten())

print("Prediction Uncertainties (StdDev):", pred_stddev.numpy().flatten())

Expected Output:
The BNN provides predictions along with uncertainty (standard deviation) for each input.
Genetic Algorithm (GA)
Objective

To optimize the coefficients of a quadratic equation using a Genetic Algorithm (GA).

Solution

Code Implementation (Quadratic Optimization):

import numpy as np

import random

# Objective function: f(x) = x^2 - 4x + 4

def fitness_function(x):

return -(x**2 - 4*x + 4) # Negative for minimization

# GA parameters

population_size = 10

generations = 100

mutation_rate = 0.1

# Initialize population

population = np.random.uniform(-10, 10, population_size)

# Genetic Algorithm

for generation in range(generations):

fitness = np.array([fitness_function(ind) for ind in population])

parents = population[np.argsort(fitness)][-2:] # Select top 2 parents

# Crossover

offspring = [(parents[0] + parents[1]) / 2 + random.uniform(-1, 1) for _ in


range(population_size - 2)]
# Mutation

offspring = [ind + random.uniform(-1, 1) if random.random() < mutation_rate else ind for ind
in offspring]

population = np.array(parents.tolist() + offspring)

best_solution = population[np.argmax([fitness_function(ind) for ind in population])]

print("Best solution found:", best_solution)

Expected Output:
The algorithm converges to the optimal solution x = 2, which minimizes the
quadratic equation.
Fuzzy Logic
Objective

To implement a fuzzy logic system for determining the "service quality" based on "food quality"
and "customer satisfaction".

Solution

Code Implementation (Fuzzy Inference System):

import skfuzzy as fuzz

from skfuzzy import control as ctrl

# Inputs

food_quality = ctrl.Antecedent(np.arange(0, 11, 1), 'food_quality')

customer_satisfaction = ctrl.Antecedent(np.arange(0, 11, 1), 'customer_satisfaction')

# Output

service_quality = ctrl.Consequent(np.arange(0, 26, 1), 'service_quality')

# Membership functions

food_quality['poor'] = fuzz.trimf(food_quality.universe, [0, 0, 5])

food_quality['average'] = fuzz.trimf(food_quality.universe, [0, 5, 10])

food_quality['good'] = fuzz.trimf(food_quality.universe, [5, 10, 10])

customer_satisfaction['low'] = fuzz.trimf(customer_satisfaction.universe, [0, 0, 5])

customer_satisfaction['medium'] = fuzz.trimf(customer_satisfaction.universe, [0, 5, 10])

customer_satisfaction['high'] = fuzz.trimf(customer_satisfaction.universe, [5, 10, 10])

service_quality['poor'] = fuzz.trimf(service_quality.universe, [0, 0, 13])

service_quality['average'] = fuzz.trimf(service_quality.universe, [0, 13, 25])

service_quality['excellent'] = fuzz.trimf(service_quality.universe, [13, 25, 25])


# Rules

rule1 = ctrl.Rule(food_quality['poor'] | customer_satisfaction['low'], service_quality['poor'])

rule2 = ctrl.Rule(food_quality['average'] & customer_satisfaction['medium'],


service_quality['average'])

rule3 = ctrl.Rule(food_quality['good'] & customer_satisfaction['high'],


service_quality['excellent'])

# Control system

service_ctrl = ctrl.ControlSystem([rule1, rule2, rule3])

service = ctrl.ControlSystemSimulation(service_ctrl)

# Input values

service.input['food_quality'] = 8

service.input['customer_satisfaction'] = 7

# Compute

service.compute()

print("Service Quality:", service.output['service_quality'])

Expected Output:
The fuzzy logic system evaluates the service quality based on given inputs and
outputs a score.

You might also like