0% found this document useful (0 votes)
15 views4 pages

Genetic Algorithm and Neural Network Code

Uploaded by

Status World
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)
15 views4 pages

Genetic Algorithm and Neural Network Code

Uploaded by

Status World
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

Code Explanation: Genetic Algorithm & Neural Network

This document provides detailed explanations of two Python programs:

1. A Genetic Algorithm to evolve a random string into a target string.

2. A Simple Neural Network built using Keras for binary classification.

Code 1: Genetic Algorithm

The genetic algorithm evolves a population of strings to match a given target string. It uses

biological evolution principles like selection, crossover, and mutation.

Key Methods:

1. random_string: Initializes a random string as the starting point.

2. fitness: Measures how close a string is to the target string.

3. crossover: Combines two parent strings to create offspring.

4. mutate: Introduces random changes for diversity.

5. genetic_algorithm: Main loop evolving the population over generations.

# Genetic Algorithm Code


import random

TARGET = "HELLO GENETIC ALGORITHM"


POPULATION_SIZE = 100
MUTATION_RATE = 0.01
GENERATIONS = 1000

def random_string(length):
return ''.join([Link]("ABCDEFGHIJKLMNOPQRSTUVWXYZ ", k=length))

def fitness(individual):
return sum(individual[i] == TARGET[i] for i in range(len(TARGET)))

def crossover(parent1, parent2):


point = [Link](1, len(TARGET) - 1)
return parent1[:point] + parent2[point:]

def mutate(individual):
return ''.join(
char if [Link]() > MUTATION_RATE else
[Link]("ABCDEFGHIJKLMNOPQRSTUVWXYZ ")
for char in individual
)

def genetic_algorithm():
population = [random_string(len(TARGET)) for _ in range(POPULATION_SIZE)]
for generation in range(GENERATIONS):
fitness_scores = [(individual, fitness(individual)) for individual in
population]
fitness_scores.sort(key=lambda x: x[1], reverse=True)
best_individual, best_score = fitness_scores[0]
print(f"Generation {generation}: {best_individual} (Fitness: {best_score})")
if best_score == len(TARGET):
print("Target string achieved!")
break
selected = [individual for individual, _ in fitness_scores[:POPULATION_SIZE //
2]]
next_generation = []
for _ in range(POPULATION_SIZE):
parent1, parent2 = [Link](selected, k=2)
offspring = crossover(parent1, parent2)
offspring = mutate(offspring)
next_generation.append(offspring)
population = next_generation
genetic_algorithm()
Code 2: Simple Neural Network Using Keras

This code demonstrates building a simple neural network for binary classification using Keras. The

model uses dense layers with ReLU and sigmoid activations to predict binary outcomes.

Key Methods:

1. make_classification: Generates synthetic data for binary classification.

2. StandardScaler: Normalizes data for better training performance.

3. Sequential: Defines the neural network's architecture.

4. compile: Configures the model with loss, optimizer, and metrics.

5. fit: Trains the model on the dataset.

6. evaluate: Tests the model's accuracy on unseen data.

# Simple Neural Network Code


from [Link] import Sequential
from [Link] import Dense
from sklearn.model_selection import train_test_split
from [Link] import make_classification
from [Link] import StandardScaler

X, y = make_classification(n_samples=1000, n_features=20, n_informative=15,


n_redundant=5, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = [Link](X_test)

model = Sequential([
Dense(64, input_dim=[Link][1], activation='relu'),
Dense(32, activation='relu'),
Dense(1, activation='sigmoid')
])

[Link](optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])


history = [Link](X_train, y_train, epochs=20, batch_size=32, validation_split=0.2,
verbose=1)
loss, accuracy = [Link](X_test, y_test, verbose=0)
print(f"Test Accuracy: {accuracy:.2f}")
predictions = ([Link](X_test) > 0.5).astype("int32")
print(f"Predictions for the first 5 samples: {predictions[:5].flatten()}")

Common questions

Powered by AI

Synthetic data, generated using methods like make_classification, allows for customizable and controlled datasets, essential for testing neural networks. It helps in creating balanced classes and controlled complexity levels, aiding in more reliable evaluation of a model's ability to learn patterns in binary classification tasks without relying on real-world data.

Splitting datasets ensures that the model is trained on one subset (training set) and evaluated on another (testing set), which is crucial for assessing its generalization ability. This separation helps prevent overfitting, as performance is measured on new, unseen data, providing a more accurate gauge of a model's real-world predictive power.

A high mutation rate increases randomness, which could lead to excessive variance and potentially degrade convergence by consistently disrupting well-adapted solutions. It might prevent the algorithm from settling on near-optimal solutions due to frequent and significant alterations, thus delaying or obstructing convergence.

Crossover combines segments of two parent strings to produce offspring, fostering genetic diversity by mixing genetic material. Mutation, on the other hand, introduces random alterations to individual strings to explore new genetic spaces. While crossover mainly drives population convergence on optimal traits, mutation prevents premature convergence by adding variability.

The choice of activation functions such as ReLU in hidden layers and sigmoid in the output layer significantly affects network performance. ReLU helps in learning nonlinear patterns by allowing independence of positive-signal propagation, while sigmoid ensures predictions are mapped to a binary range, essential for tasks involving binary outcomes.

The fitness of an individual string is measured by comparing each character in the string to the corresponding character in the target string. The fitness score is the count of matching characters. It is crucial because it quantifies how close an individual is to the target, guiding selection towards more suitable candidates.

The genetic algorithm applies principles analogous to natural selection to evolve solutions towards a target. It uses selection to choose strings with higher fitness scores, crossover to combine attributes of parent strings, and mutation to introduce random variations for diversity. This iterative process gradually improves the population's average fitness score until a string matches the target.

The dense layers with ReLU activation function as computational layers that transform the input through learned weights, enabling the network to model complex patterns. The output dense layer with a sigmoid activation compresses the input value to a probability between 0 and 1, making it suitable for binary classification tasks.

Using StandardScaler normalizes the features by removing the mean and scaling to unit variance, which helps improve the model's training efficiency. It can influence convergence speed and the stability of weights during training because the optimizer benefits from features with similar scales.

The genetic algorithm stops when it achieves a string with a fitness score equal to the length of the target string, indicating a perfect match. Alternatively, it stops after a predefined number of generations if the target string has not been matched. This dual condition ensures completion regardless of performance.

You might also like