Genetic Algorithm and Neural Network
Genetic Algorithm and Neural Network
The genetic algorithm evolves a population of strings to match a given target string. It uses
Key Methods:
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 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:
model = Sequential([
Dense(64, input_dim=X.shape[1], activation='relu'),
Dense(32, activation='relu'),
Dense(1, activation='sigmoid')
])