Genetic algoritm generating the text

Joined
Aug 18, 2023
Messages
1
Reaction score
0
Hello, I composed this code but I would like to be able to improve the idea, can you help me? Thank you
Python:
import random

# Load the dataset
train_data = """ Put your text to train code here...  """ # load train data here

def get_random_prompt():
    dataset = train_data
    # Split the dataset into individual words
    words = dataset.split(' ')

    # Select a random word from the dataset
    word = random.choice(words)

    # Return the selected word
    print("Prompt : " + word + "\n")
    word = word + " "
    return word

def evaluate_fitness(individual):
    # Evaluate the fitness of the individual
    return len(individual)


def mutate(text):
    # Randomly change a word in the text
    word_indices = list(range(len(text)))
    index = random.randint(0, len(text) - 1)
    old_word = text[index]
    new_word = get_random_prompt()
    text = text[:index] + new_word + text[index + 1:]
    return text

def crossover(parent1, parent2):
    # Randomly choose a segment of the first parent to use as the starting point for the offspring
    start_index1 = random.randint(0, len(parent1) - 1)

    # Determine the length of the offspring based on the second parent
    length = min(len(parent2), len(parent1) - start_index1)

    # Create the offspring by combining the segments of the two parents
    offspring1 = parent1[start_index1:] + parent2[:length]
    offspring2 = parent2[length:] + parent1[:start_index1]

    return offspring1, offspring2


def evolve_text(max_length=100):
    # Initialize the population
    population = [get_random_prompt() for _ in range(100)]

    # Evolve the population
    generations = 30
    for i in range(generations):
        select_parents = random.sample(population, 2)
        crossover_rate = 0.7
        mutation_rate = 0.3

        for _ in range(2):
            if random.uniform(0, 1) < crossover_rate:
                parent1, parent2 = select_parents
                offspring1, offspring2 = crossover(parent1, parent2)
                population.extend([offspring1, offspring2])
            elif random.uniform(0, 1) < mutation_rate:
                text = random.choice(population)
                mutated_text = mutate(text)
                population.remove(text)
                population.append(mutated_text)

        print('Generation', i + 1, 'complete.')

    # Output the best solution
    best_solution = None
    best_score = -1
    for text in population:
        score = evaluate_fitness(text)
        if score > best_score:
            best_score = score
            best_solution = text
    print('Best solution:', best_solution)





# Evolve the text
evolve_text()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,061
Latest member
KetonaraKeto

Latest Threads

Top