0% found this document useful (0 votes)
6 views

Soft Computing File

soft computing

Uploaded by

rajifat462
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)
6 views

Soft Computing File

soft computing

Uploaded by

rajifat462
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/ 27

1.

Write a program for implementing linear saturating


function.

public class LinearSaturatingFunction {


public static double saturatingLinear(double x, double lowerBound, double
upperBound) {
if (x < lowerBound) {
return lowerBound;
}
else if (x > upperBound) {
return upperBound;
}
else {
return x;
}
}

public static void main(String[] args) {


double lowerBound = -5.0;
double upperBound = 5.0;
double[] testValues = {-10, -5, -3, 0, 3, 5, 10};

System.out.println("Linear Saturating Function Output:");


for (double value : testValues) {
double result = saturatingLinear(value, lowerBound, upperBound);
System.out.printf("Input: %f, Output: %f%n", value, result);
}
}
}

1
Output-

2
2. Generate ANDNOT function using McCulloch-Pitts neural
net.
public class ANDNOTFunction {
public static int andNot(int inputA, int inputB) {

int weightA = 1;
int weightB = -1;
double threshold = 0.5;
double weightedSum = (inputA * weightA) + (inputB * weightB);
return (weightedSum >= threshold) ? 1 : 0;
}
public static void main(String[] args) {
int[][] truthTable = {
{0, 0},
{0, 1},
{1, 0},
{1, 1}
};
System.out.println("A B Output (A AND NOT B)");
for (int[] inputs : truthTable) {
int output = andNot(inputs[0], inputs[1]);
System.out.printf("%d %d %d%n", inputs[0], inputs[1], output);
}
}
}

Output-

3
3. Generate XOR function using McCulloch-Pitts neural net.
public class XORFunction {

private static int andNot(int inputA, int inputB) {


int weightA = 1;
int weightB = -1;
double threshold = 0.5;

double weightedSum = (inputA * weightA) + (inputB * weightB);


return (weightedSum >= threshold) ? 1 : 0;
}

private static int or(int inputA, int inputB) {


int weightA = 1;
int weightB = 1;
double threshold = 0.5;

double weightedSum = (inputA * weightA) + (inputB * weightB);


return (weightedSum >= threshold) ? 1 : 0;
}

public static int xor(int inputA, int inputB) {


int term1 = andNot(inputA, inputB);
int term2 = andNot(inputB, inputA);

return or(term1, term2);


}

public static void main(String[] args) {


int[][] truthTable = {
{0, 0},
{0, 1},
{1, 0},
{1, 1}
};

System.out.println("A B Output (A XOR B)");


for (int[] inputs : truthTable) {
4
int output = xor(inputs[0], inputs[1]);
System.out.printf("%d %d %d%n", inputs[0], inputs[1], output);
}
}
}

Output-

5
4. Write a program to implement Hebb's Net to classify two
dimensional input patterns in bipolar with given targets.
public class HebbsNet {
private double[] weights;
private double bias;

public HebbsNet(int inputSize) {


weights = new double[inputSize];
bias = 0.0;
}

public void train(double[][] inputs, double[] targets) {


for (int i = 0; i < inputs.length; i++) {
for (int j = 0; j < inputs[i].length; j++) {
weights[j] += inputs[i][j] * targets[i];
}
bias += targets[i];
}
}

public int predict(double[] input) {


double netInput = bias;
for (int i = 0; i < input.length; i++) {
netInput += weights[i] * input[i];
}
return (netInput >= 0) ? 1 : -1;
}

public static void main(String[] args) {


double[][] inputs = {

6
{1, 1},
{1, -1},
{-1, 1},
{-1, -1}
};

double[] targets = {1, -1, -1, -1};


HebbsNet hebbsNet = new HebbsNet(2);
hebbsNet.train(inputs, targets);

System.out.println("Testing Hebb's Net:");


for (int i = 0; i < inputs.length; i++) {
int output = hebbsNet.predict(inputs[i]);
System.out.printf("Input: (%.1f, %.1f) -> Predicted Output: %d, Target:
%.0f%n",
inputs[i][0], inputs[i][1], output, targets[i]);
}
}
}

Output-

7
5. Perceptron net for an AND function with bipolar inputs
and targets.
public class PerceptronAND {

private static final int MAX_EPOCHS = 1000;


private static final double LEARNING_RATE = 0.1;
private static final int NUM_INPUTS = 2;
private double[] weights = new double[NUM_INPUTS];
private double bias = 0;

public PerceptronAND() {
for (int i = 0; i < NUM_INPUTS; i++) {
weights[i] = Math.random() * 2 - 1;
}
bias = Math.random() * 2 - 1;
}

private int activationFunction(double input) {


return input >= 0 ? 1 : -1;
}

private int calculateOutput(int[] inputs) {


double weightedSum = 0;
for (int i = 0; i < NUM_INPUTS; i++) {
weightedSum += weights[i] * inputs[i];
}
weightedSum += bias;
return activationFunction(weightedSum);
}

8
public void train(int[][] inputs, int[] targets) {
int epoch = 0;
boolean isConverged = false;

while (epoch < MAX_EPOCHS && !isConverged) {


isConverged = true;
for (int i = 0; i < inputs.length; i++) {
int[] input = inputs[i];
int target = targets[i];
int output = calculateOutput(input);
int error = target - output;

if (error != 0) {
isConverged = false;
for (int j = 0; j < NUM_INPUTS; j++) {
weights[j] += LEARNING_RATE * error * input[j];
}
bias += LEARNING_RATE * error;
}
}
epoch++;
}

if (isConverged) {
System.out.println("Training completed in " + epoch + " epochs.");
}
else {
System.out.println("Training did not converge in the given epochs.");
}
}
public void test(int[][] inputs) {
9
System.out.println("Testing the perceptron:");
for (int[] input : inputs) {
int output = calculateOutput(input);
System.out.println("Input: [" + input[0] + ", " + input[1] + "] => Output: "
+ output);
}
}

public static void main(String[] args) {


int[][] inputs = {
{-1, -1},
{-1, 1},
{1, -1},
{1, 1}
};
int[] targets = {-1, -1, -1, 1};
PerceptronAND perceptron = new PerceptronAND();
perceptron.train(inputs, targets);
perceptron.test(inputs);
}
}

Output-

10
6. Write a program of Perceptron Training Algorithm.
public class Perceptron {
private double[] weights;
private double bias;
private double learningRate;

public Perceptron(int inputSize, double learningRate) {


this.weights = new double[inputSize];
this.bias = 0.0;
this.learningRate = learningRate;
}
public void train(double[][] inputs, int[] targets, int maxEpochs) {
int epoch = 0;
boolean hasError;
do {
hasError = false;
for (int i = 0; i < inputs.length; i++) {
int prediction = predict(inputs[i]);
int error = targets[i] - prediction;

if (error != 0) {
for (int j = 0; j < weights.length; j++) {
weights[j] += learningRate * error * inputs[i][j];
}
bias += learningRate * error;
hasError = true;
}
}
epoch++;
}
while (hasError && epoch < maxEpochs);
System.out.println("Training completed in " + epoch + " epochs.");

11
}
public int predict(double[] input) {
double netInput = bias;
for (int i = 0; i < input.length; i++) {
netInput += weights[i] * input[i];
}
return (netInput >= 0) ? 1 : -1;
}
public static void main(String[] args) {
double[][] inputs = {
{0, 0},
{0, 1},
{1, 0},
{1, 1}
};
int[] targets = {-1, 1, 1, 1};
Perceptron perceptron = new Perceptron(2, 0.1);
perceptron.train(inputs, targets, 100);
System.out.println("Testing Perceptron:");
for (int i = 0; i < inputs.length; i++) {
int output = perceptron.predict(inputs[i]);
System.out.printf("Input: (%.1f, %.1f) -> Predicted Output: %d, Target: %d%n",
inputs[i][0], inputs[i][1], output, targets[i]);
}
}
}

Output-

12
7. Write a program for Back Propagation Algorithm.
import java.util.Random;
public class BackPropagation {
private static final int INPUT_NEURONS = 2;
private static final int HIDDEN_NEURONS = 2;
private static final int OUTPUT_NEURONS = 1;
private static final double LEARNING_RATE = 0.5;

private double[] hiddenLayer = new double[HIDDEN_NEURONS];


private double[] outputLayer = new double[OUTPUT_NEURONS];
private double[][] inputToHiddenWeights = new
double[INPUT_NEURONS][HIDDEN_NEURONS];
private double[] hiddenBias = new double[HIDDEN_NEURONS];
private double[][] hiddenToOutputWeights = new
double[HIDDEN_NEURONS][OUTPUT_NEURONS];
private double[] outputBias = new double[OUTPUT_NEURONS];

public BackPropagation() {
initializeWeights();
}

private void initializeWeights() {


Random random = new Random();
for (int i = 0; i < INPUT_NEURONS; i++) {
for (int j = 0; j < HIDDEN_NEURONS; j++) {
inputToHiddenWeights[i][j] = random.nextDouble() - 0.5;
}
}

13
for (int i = 0; i < HIDDEN_NEURONS; i++) {
hiddenBias[i] = random.nextDouble() - 0.5;
for (int j = 0; j < OUTPUT_NEURONS; j++) {
hiddenToOutputWeights[i][j] = random.nextDouble() - 0.5;
}
}
for (int i = 0; i < OUTPUT_NEURONS; i++) {
outputBias[i] = random.nextDouble() - 0.5;
}
}

private double sigmoid(double x) {


return 1 / (1 + Math.exp(-x));
}
private double sigmoidDerivative(double x) {
return x * (1 - x);
}

public void train(double[][] inputs, double[][] targets, int epochs) {


for (int epoch = 0; epoch < epochs; epoch++) {
double totalError = 0.0;
for (int sample = 0; sample < inputs.length; sample++) {
forward(inputs[sample]);
double[] outputErrors = new double[OUTPUT_NEURONS];
double[] outputDeltas = new double[OUTPUT_NEURONS];
for (int i = 0; i < OUTPUT_NEURONS; i++) {
outputErrors[i] = targets[sample][i] - outputLayer[i];
outputDeltas[i] = outputErrors[i] * sigmoidDerivative(outputLayer[i]);
totalError += Math.pow(outputErrors[i], 2);
}

14
double[] hiddenErrors = new double[HIDDEN_NEURONS];
double[] hiddenDeltas = new double[HIDDEN_NEURONS];
for (int i = 0; i < HIDDEN_NEURONS; i++) {
hiddenErrors[i] = 0.0;
for (int j = 0; j < OUTPUT_NEURONS; j++) {
hiddenErrors[i] += outputDeltas[j] * hiddenToOutputWeights[i][j];
}
hiddenDeltas[i] = hiddenErrors[i] * sigmoidDerivative(hiddenLayer[i]);
for (int i = 0; i < HIDDEN_NEURONS; i++) {
hiddenBias[i] += LEARNING_RATE * hiddenDeltas[i];
}
}
System.out.printf("Epoch %d: Total Error = %.6f%n", epoch + 1, totalError / 2);
}
}

outputLayer[i] += outputBias[i];
outputLayer[i] = sigmoid(outputLayer[i]);
}
}

public double[] predict(double[] inputs) {


forward(inputs);
return outputLayer;
}
public static void main(String[] args) {
double[][] inputs = {
{0, 0},
{0, 1},
15
{1, 0},
{1, 1}
};
double[][] targets = {
{0},
{1},
{1},
{0}
};

BackPropagation neuralNet = new BackPropagation();


neuralNet.train(inputs, targets, 10000);
System.out.println("Testing Neural Network:");
for (double[] input : inputs) {
double[] output = neuralNet.predict(input);
System.out.printf("Input: %.1f, %.1f -> Predicted Output: %.4f%n",
input[0], input[1], output[0]);
}
}
}

Output-

16
8. Write a program to implement logic gates.
import java.util.Scanner;
public class LogicGates {

public static int andGate(int a, int b) {


return a & b;
}
public static int orGate(int a, int b) {
return a | b;
}
public static int notGate(int a) {
return a == 0 ? 1 : 0;
}
public static int nandGate(int a, int b) {
return notGate(andGate(a, b));
}
public static int norGate(int a, int b) {
return notGate(orGate(a, b));
}
public static int xorGate(int a, int b) {
return a ^ b;
}
public static int xnorGate(int a, int b) {
return notGate(xorGate(a, b));
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

17
System.out.println("Welcome to the Logic Gates Simulator!");
System.out.print("Enter the first binary value (0 or 1): ");
int a = scanner.nextInt();
System.out.print("Enter the second binary value (0 or 1): ");
int b = scanner.nextInt();

if ((a != 0 && a != 1) || (b != 0 && b != 1)) {


System.out.println("Invalid input. Please enter binary values (0 or 1).");
return;
}
System.out.println("Select the logic gate to apply:");
System.out.println("1. AND");
System.out.println("2. OR");
System.out.println("3. NOT (applies to the first input only)");
System.out.println("4. NAND");
System.out.println("5. NOR");
System.out.println("6. XOR");
System.out.println("7. XNOR");
System.out.print("Enter your choice (1-7): ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("AND Gate Output: " + andGate(a, b));
break;
case 2:
System.out.println("OR Gate Output: " + orGate(a, b));
break;
case 3:
System.out.println("NOT Gate Output (for first input): " + notGate(a));
break;
case 4:
18
System.out.println("NAND Gate Output: " + nandGate(a, b));
break;
case 5:
System.out.println("NOR Gate Output: " + norGate(a, b));
break;
case 6:
System.out.println("XOR Gate Output: " + xorGate(a, b));
break;
case 7:
System.out.println("XNOR Gate Output: " + xnorGate(a, b));
break;
default:
System.out.println("Invalid choice. Please select a number between 1
and 7.");
}
scanner.close();
}
}

Output-

19
9. To perform Union, Intersection and Complement
operations.
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class SetOperations {
public static Set<Integer> union(Set<Integer> setA, Set<Integer> setB) {
Set<Integer> resultSet = new HashSet<>(setA);
resultSet.addAll(setB);
return resultSet;
}
public static Set<Integer> intersection(Set<Integer> setA, Set<Integer> setB) {
Set<Integer> resultSet = new HashSet<>(setA);
resultSet.retainAll(setB);
return resultSet;
}

public static Set<Integer> complement(Set<Integer> universalSet,


Set<Integer> setA) {
Set<Integer> resultSet = new HashSet<>(universalSet);
resultSet.removeAll(setA);
return resultSet;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the elements of the Universal Set (comma-
separated): ");
String[] universalInput = scanner.nextLine().split(",");
Set<Integer> universalSet = new HashSet<>();
for (String s : universalInput) {
20
universalSet.add(Integer.parseInt(s.trim()));
}
System.out.print("Enter the elements of Set A (comma-separated): ");
String[] setAInput = scanner.nextLine().split(",");
Set<Integer> setA = new HashSet<>();
for (String s : setAInput) {
setA.add(Integer.parseInt(s.trim()));
}
System.out.print("Enter the elements of Set B (comma-separated): ");
String[] setBInput = scanner.nextLine().split(",");
Set<Integer> setB = new HashSet<>();
for (String s : setBInput) {
setB.add(Integer.parseInt(s.trim()));
}
System.out.println("Union of A and B: " + union(setA, setB));
System.out.println("Intersection of A and B: " + intersection(setA, setB));
System.out.println("Complement of A: " + complement(universalSet,
setA));
System.out.println("Complement of B: " + complement(universalSet,
setB));
scanner.close();
}

Input-

Output-

21
10. To plot various membership functions.
import java.io.FileWriter;
import java.io.IOException;

public class MembershipFunctions {

public static double triangular(double x, double a, double b, double c) {


if (x <= a || x >= c) return 0;
else if (x < b) return (x - a) / (b - a);
else return (c - x) / (c - b);
}

public static double trapezoidal(double x, double a, double b, double c,


double d) {
if (x <= a || x >= d) return 0;
else if (x < b) return (x - a) / (b - a);
else if (x <= c) return 1;
else return (d - x) / (d - c);
}

public static double gaussian(double x, double mean, double sigma) {


return Math.exp(-Math.pow(x - mean, 2) / (2 * Math.pow(sigma, 2)));
}

public static double sigmoidal(double x, double a, double c) {


return 1 / (1 + Math.exp(-a * (x - c)));
}

public static void main(String[] args) {


double[] xValues = new double[100];
for (int i = 0; i < xValues.length; i++) {
xValues[i] = -10 + i * 0.2;
}

try (FileWriter writer = new FileWriter("membership_functions.csv")) {


writer.write("x,Triangular,Trapezoidal,Gaussian,Sigmoidal\n");
for (double x : xValues) {
double triangular = triangular(x, -5, 0, 5);
22
double trapezoidal = trapezoidal(x, -7, -5, 5, 7);
double gaussian = gaussian(x, 0, 2);
double sigmoidal = sigmoidal(x, 1, 0);

writer.write(String.format("%.2f,%.4f,%.4f,%.4f,%.4f\n", x, triangular,
trapezoidal, gaussian, sigmoidal));
}
System.out.println("Membership function data exported to
'membership_functions.csv'");
}
catch (IOException e) {
e.printStackTrace();
}
}
}

Output-

23
11. To implement Genetic Algorithm.
import java.util.Random;
public class GeneticAlgorithm {

private static final int POPULATION_SIZE = 6;


private static final int CHROMOSOME_LENGTH = 5;
private static final int MAX_GENERATIONS = 50;
private static final double CROSSOVER_RATE = 0.8;
private static final double MUTATION_RATE = 0.1;
private static final Random random = new Random();
public static void main(String[] args) {
int[][] population = initializePopulation();

for (int generation = 1; generation <= MAX_GENERATIONS; generation++) {

int[] fitness = evaluateFitness(population);


int[][] parents = selectParents(population, fitness);
int[][] offspring = crossover(parents);
mutate(offspring);
population = offspring;
int bestIndex = getBestIndividualIndex(fitness);
int bestValue = binaryToDecimal(population[bestIndex]);
System.out.printf("Generation %d: Best x = %d, f(x) = %d%n",
generation, bestValue, bestValue * bestValue);
}
}

private static int[][] initializePopulation() {


int[][] population = new int[POPULATION_SIZE][CHROMOSOME_LENGTH];
for (int i = 0; i < POPULATION_SIZE; i++) {

24
for (int j = 0; j < CHROMOSOME_LENGTH; j++) {
population[i][j] = random.nextInt(2);
}
}
return population;
}
private static int[] evaluateFitness(int[][] population) {
int[] fitness = new int[POPULATION_SIZE];
for (int i = 0; i < POPULATION_SIZE; i++) {
int value = binaryToDecimal(population[i]);
fitness[i] = value * value;
}
return fitness;
}

private static int[][] selectParents(int[][] population, int[] fitness) {


int[][] parents = new int[POPULATION_SIZE][CHROMOSOME_LENGTH];
int totalFitness = 0;
for (int fit : fitness) {
totalFitness += fit;
}
for (int i = 0; i < POPULATION_SIZE; i++) {
int rand = random.nextInt(totalFitness);
int cumulative = 0;
for (int j = 0; j < POPULATION_SIZE; j++) {
cumulative += fitness[j];
if (cumulative > rand) {
parents[i] = population[j].clone();
break;
}
25
}
}
return parents;
}

private static int[][] crossover(int[][] parents) {


int[][] offspring = new int[POPULATION_SIZE][CHROMOSOME_LENGTH];
for (int i = 0; i < POPULATION_SIZE; i += 2) {
if (i + 1 < POPULATION_SIZE && random.nextDouble() < CROSSOVER_RATE)
{
int crossoverPoint = random.nextInt(CHROMOSOME_LENGTH - 1) + 1;
for (int j = 0; j < CHROMOSOME_LENGTH; j++) {
if (j < crossoverPoint) {
offspring[i][j] = parents[i][j];
offspring[i + 1][j] = parents[i + 1][j];
}
else {
offspring[i][j] = parents[i + 1][j];
offspring[i + 1][j] = parents[i][j];
}
}
}
else {
offspring[i] = parents[i].clone();
if (i + 1 < POPULATION_SIZE) {
offspring[i + 1] = parents[i + 1].clone();
}
}
}
return offspring;
}
private static void mutate(int[][] offspring) {
26
for (int i = 0; i < POPULATION_SIZE; i++) {
for (int j = 0; j < CHROMOSOME_LENGTH; j++) {
if (random.nextDouble() < MUTATION_RATE) {
offspring[i][j] = 1 - offspring[i][j];
}
}
}
}
private static int binaryToDecimal(int[] chromosome) {
int value = 0;
for (int i = 0; i < CHROMOSOME_LENGTH; i++) {
value += chromosome[i] * Math.pow(2, CHROMOSOME_LENGTH - i - 1);
}
return value;
}

private static int getBestIndividualIndex(int[] fitness) {


int bestIndex = 0;
for (int i = 1; i < fitness.length; i++) {
if (fitness[i] > fitness[bestIndex]) {
bestIndex = i;
}
}
return bestIndex;
}
}

Output-

27

You might also like