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

Genetic Algorithm and Neural Network

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)
10 views4 pages

Genetic Algorithm and Neural Network

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
You are on page 1/ 4

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(random.choices("ABCDEFGHIJKLMNOPQRSTUVWXYZ ", k=length))

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

def crossover(parent1, parent2):


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

def mutate(individual):
return ''.join(
char if random.random() > MUTATION_RATE else
random.choice("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 = random.choices(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 keras.models import Sequential
from keras.layers import Dense
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_classification
from sklearn.preprocessing 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 = scaler.transform(X_test)

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

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


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

You might also like