You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python遗传算法如何获取ASCII表指定区间值优化运行速度

遗传算法ASCII区间筛选实现方案

你需要调整合法ASCII取值集合,同时修改种群初始化、变异两个环节的随机取值逻辑,就能实现仅保留9-10、32-127区间ASCII值的需求,同时搜索空间缩小18%左右,能有效提升算法收敛速度。

核心修改点

  • 替换原单区间边界定义为合法ASCII数组,直接预生成所有允许的取值
  • 种群初始化逻辑从区间随机取值改为从合法数组中随机选择
  • 变异逻辑的取值来源同步替换为合法数组

修改后完整代码

import numpy as np

TARGET_PHRASE = """The smartest and fastest Pixel yet.

Google Tensor: Our first custom-built processor.
The first processor designed by Google and made for Pixel, Tensor makes the new Pixel phones our most powerful yet.

The most advanced Pixel Camera ever.
Capture brilliant color and vivid detail with Pixels best-in-class computational photography and new pro-level lenses."""       # target DNA
POP_SIZE = 4000                      # population size
CROSS_RATE = 0.8                    # mating probability (DNA crossover)
MUTATION_RATE = 0.00001                # mutation probability
N_GENERATIONS = 100000

DNA_SIZE = len(TARGET_PHRASE)
TARGET_ASCII = np.fromstring(TARGET_PHRASE, dtype=np.uint8)  # convert string to number
# 替换原区间定义,预生成所有合法ASCII值:9-10(制表符、换行符) + 32-127(可打印字符)
ALLOWED_ASCII = np.concatenate([np.arange(9, 11), np.arange(32, 128)])


class GA(object):
    def __init__(self, DNA_size, cross_rate, mutation_rate, pop_size):
        self.DNA_size = DNA_size
        self.cross_rate = cross_rate
        self.mutate_rate = mutation_rate
        self.pop_size = pop_size

        # 从合法ASCII数组中随机取值初始化种群,移除原区间随机逻辑
        self.pop = np.random.choice(ALLOWED_ASCII, size=(pop_size, DNA_size)).astype(np.int8)  # int8 for convert to ASCII

    def translateDNA(self, DNA):                 # convert to readable string
        return DNA.tostring().decode('ascii')

    def get_fitness(self):                      # count how many character matches
        match_count = (self.pop == TARGET_ASCII).sum(axis=1)
        return match_count

    def select(self):
        fitness = self.get_fitness()     # add a small amount to avoid all zero fitness
        idx = np.random.choice(np.arange(self.pop_size), size=self.pop_size, replace=True, p=fitness/fitness.sum())
        return self.pop[idx]

    def crossover(self, parent, pop):
        if np.random.rand() < self.cross_rate:
            i_ = np.random.randint(0, self.pop_size, size=1)                        # select another individual from pop
            cross_points = np.random.randint(0, 2, self.DNA_size).astype(np.bool)   # choose crossover points
            parent[cross_points] = pop[i_, cross_points]                            # mating and produce one child
        return parent

    def mutate(self, child):
        for point in range(self.DNA_size):
            if np.random.rand() < self.mutate_rate:
                # 变异时仅从合法ASCII数组中取值,移除原区间随机逻辑
                child[point] = np.random.choice(ALLOWED_ASCII)
        return child

    def evolve(self):
        pop = self.select()
        pop_copy = pop.copy()
        for parent in pop:  # for every parent
            child = self.crossover(parent, pop_copy)
            child = self.mutate(child)
            parent[:] = child
        self.pop = pop

if __name__ == '__main__':
    ga = GA(DNA_size=DNA_SIZE, cross_rate=CROSS_RATE,
            mutation_rate=MUTATION_RATE, pop_size=POP_SIZE)

    for generation in range(N_GENERATIONS):
        fitness = ga.get_fitness()
        best_DNA = ga.pop[np.argmax(fitness)]
        best_phrase = ga.translateDNA(best_DNA)
        print('Gen', generation, ': ', best_phrase)
        if best_phrase == TARGET_PHRASE:
            break
        ga.evolve()

该实现无需额外判断过滤无效ASCII值,几乎没有额外性能损耗,完全匹配你提升运行速度的需求。

内容的提问来源于stack exchange,提问作者Raz0rmaddnes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 07:15:03