Practical Assignment 2
Practical Assignment 2
def sigmoid_derivative(x):
return x * (1 - x)
hidden_error = output_delta.dot(self.weights_hidden_output.T)
hidden_delta = hidden_error * sigmoid_derivative(self.hidden_output)
# Example usage
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) # XOR inputs
y = np.array([[0], [1], [1], [0]]) # XOR outputs
nn = SimpleANN(input_size=2, hidden_size=2, output_size=1)
nn.train(X, y)
print("Output after training:")
print(nn.forward(X))
def sigmoid_derivative(x):
return x * (1 - x)
class NeuralNetworkWithBackprop:
def __init__(self, input_size, hidden_size, output_size, learning_rate=0.1):
self.learning_rate = learning_rate
# Initialize weights and biases
self.weights_input_hidden = np.random.rand(input_size, hidden_size)
self.weights_hidden_output = np.random.rand(hidden_size, output_size)
self.bias_hidden = np.random.rand(1, hidden_size)
self.bias_output = np.random.rand(1, output_size)
hidden_error = output_delta.dot(self.weights_hidden_output.T)
hidden_delta = hidden_error * sigmoid_derivative(self.hidden_output)
# Example usage
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) # XOR inputs
y = np.array([[0], [1], [1], [0]]) # XOR outputs
nn = NeuralNetworkWithBackprop(input_size=2, hidden_size=2, output_size=1)
nn.train(X, y)
print("Output after training:")
print(nn.forward(X))
deltas.reverse()
for i in range(len(self.weights)):
self.weights[i] += self.layer_outputs[i].T.dot(deltas[i]) * self.learning_rate
self.biases[i] += np.sum(deltas[i], axis=0, keepdims=True) *
self.learning_rate
# Example usage
layer_sizes = [2, 4, 3, 1] # input layer, two hidden layers, and output layer
deep_nn = DeepNN(layer_sizes)
deep_nn.train(X, y)
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
# XOR dataset
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]])
# Fitness function
def fitness(candidate):
return sum(1 for expected, actual in zip(target, candidate) if expected ==
actual)
# Mutate a string
def mutate(string):
new_string = ''
for char in string:
if random.random() < mutation_rate:
new_string += random.choice('abcdefghijklmnopqrstuvwxyz ')
else:
new_string += char
return new_string
# Crossover
def crossover(parent1, parent2):
midpoint = random.randint(0, len(target))
return parent1[:midpoint] + parent2[midpoint:]
# Genetic Algorithm
population = [random_string(len(target)) for _ in range(population_size)]
for generation in range(generation_limit):
population = sorted(population, key=fitness, reverse=True)
if fitness(population[0]) == len(target):
print(f"Target string '{target}' created in generation {generation}")
break
next_population = population[:10] # Keep top 10
for _ in range(population_size - 10):
parent1, parent2 = random.sample(next_population, 2)
child = crossover(parent1, parent2)
next_population.append(mutate(child))
population = next_population
6) Write program to Implement travelling salesman problem using
genetic algorithm.
→
import random
import numpy as np
# Distance calculation
def distance(a, b):
return np.linalg.norm(a - b)
# Mutation
def mutate(route):
a, b = random.sample(range(len(route)), 2)
route[a], route[b] = route[b], route[a]
# Crossover
def crossover(parent1, parent2):
start, end = sorted(random.sample(range(len(parent1)), 2))
child = [None] * len(parent1)
child[start:end] = parent1[start:end]
ptr = 0
for gene in parent2:
if gene not in child:
while child[ptr] is not None:
ptr += 1
child[ptr] = gene
return child
# Genetic Algorithm
population_size = 100
population = [random.sample(range(num_cities), num_cities) for _ in
range(population_size)]
generations = 500
# Mutation
def mutate(individual):
return [gene if random.random() > mutation_rate else 1 - gene for gene in
individual]
# Crossover
def crossover(parent1, parent2):
point = random.randint(1, len(target) - 1)
return parent1[:point] + parent2[point:]
# Genetic Algorithm
population = [random_individual() for _ in range(population_size)]
best_fitness_over_time = []
if best_fitness == len(target):
print(f"Target reached in generation {generation}")
break