程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

快乐8预测遗传算法的实现逻辑

hfteth 2025-01-18 20:04:11 技术文章 14 ℃

这是一个python遗传算法的代码,用于优化彩票快乐8号码的预测。

快乐8预测遗传算法的实现逻辑如下:

首先定义一个快乐8历史数据列表,其中包含了过去的一些快乐8号码。

然后定义了遗传算法的参数,包括种群大小、迭代次数、交叉概率和变异概率等。

import random

import numpy as np

from deap import algorithms, base, creator, tools

# 快乐8历史数据

history = [[4,5,7,10,14,17,21,28,29,31,42,43,60,62,64,66,68,73,74,75],

[6,14,21,23,24,27,29,34,38,40,42,45,47,54,60,65,67,72,74,75],

[1,2,6,9,17,18,22,24,30,36,40,41,46,48,51,52,58,68,73,75],

[2,5,9,11,21,22,26,32,43,46,47,51,53,55,56,60,61,65,76,77],

[3,4,6,8,17,22,23,35,40,42,43,45,47,50,55,58,65,66,67,80],

[8,28,31,42,46,47,49,53,54,55,58,60,64,67,68,70,71,72,75,79],

[1,3,5,7,11,16,17,18,20,27,33,34,41,42,53,57,59,69,71,77],

[6,8,16,18,20,21,29,31,33,40,47,49,55,56,57,66,69,70,74,80]]

接着定义了适应度函数,用于评估一个个体的适应度。在这个函数中,对于每个个体,遍历它包含的每个数字,并判断该数字是否出现在历史数据中。如果是,则适应度加1。

POPULATION_SIZE = 100

NUM_GENERATIONS = 50

CROSSOVER_PROBABILITY = 0.5

MUTATION_PROBABILITY = 0.2

定义适应度函数

def fitness_function(individual):

计算个体的适应度

score = 0

for number in individual:

if number in history:

score += 1

return score,

创建了遗传算法的工具箱,并注册了各种操作函数和评估函数。

creator.create("FitnessMax", base.Fitness, weights=(1.0,))

creator.create("Individual", list, fitness=creator.FitnessMax)

toolbox = base.Toolbox()

toolbox.register("attr_number", random.randint, 1, 80)

toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_number, n=10)

toolbox.register("population", tools.initRepeat, list, toolbox.individual)

toolbox.register("evaluate", fitness_function)

toolbox.register("mate", tools.cxTwoPoint)

toolbox.register("mutate", tools.mutUniformInt, low=1, up=80, indpb=0.05)

toolbox.register("select", tools.selTournament, tournsize=3)

运行遗传算法,并输出最优解。

population = toolbox.population(n=POPULATION_SIZE)

for generation in range(NUM_GENERATIONS):

offspring = algorithms.varAnd(population, toolbox, CROSSOVER_PROBABILITY, MUTATION_PROBABILITY)

fits = toolbox.map(toolbox.evaluate, offspring)

for fit, ind in zip(fits, offspring):

ind.fitness.values = fit

population = toolbox.select(offspring, k=len(population))

输出最优解

best_individual = tools.selBest(population, k=1)[0]

print("优化后的快乐8号码为:", best_individual)

运行多次的汇总结果如下:

[41, 79, 64, 3, 53, 9, 80, 18, 67, 43]

[14, 77, 31, 5, 80, 46, 42, 47, 9, 64]

[71, 1, 4, 14, 31, 17, 22, 42, 40, 3]

[31, 16, 6, 5,28, 17, 14, 22, 41, 47]

[21, 64, 54, 73, 67, 31, 14, 42, 46, 79]

[60, 43,, 40, 8, 54, 71, 79, 47, 21, 22]

[53, 43, 8, 11, 28, 67, 14, 47, 6, 16]

【数据为代码生成,仅供学习研究之用!】

快乐8实际上很适合守号,很多选2玩法的大牛多采用守号,逐渐加倍策略。

附录:

快乐8近期统计 - 出现概率排前35的号码为:

18 47 41 17 64 53 5 42 1 11 31 43 54 77 3 4 21 60 6 9 8 79 16 14 28 73 24 40 65 67 2 22 46 80 71

热门同出两码:

60+31

14+29

17+66

41+18

72+47

14+31

热门号码汇总:4.17.41.18.69.71.75.60.79.29.14.17

温号排行汇总:28.42.21.5.6.64.65.73.77.80.68.24.67

Tags:

最近发表
标签列表