遗传算法Genetic algorithm

def model(params, x):
    a1,a2,a3,a4,a5,a6 = params
    x_w = (a1*x[0] + a2*x[1] + a3*x[2] + a4*x[3] + a5*x[4] + a6*x[5])/(a1+a2+a3+a4+a5+a6)
    return x_w

# =============================================================================
# def objective_function(params,x,y):
#     x_w =model(params,x)
#     NSE = fun_NSE(x_w,y)
#     NSE_med = np.nanmedian(NSE)
#     return NSE_med
# =============================================================================
def objective_function(params,x,y):
    x_w =model(params,x)
    NSE = fun_NSE(x_w,y)
    NSE_med = np.nanmedian(NSE)
    return (NSE_med,)

# =============================================================================
# 
# from deap import base, creator, tools, algorithms
# # 遗传算法设置
# creator.create("FitnessMin", base.Fitness, weights=(1.0,))
# creator.create("Individual", list, fitness=creator.FitnessMin)
# 
# toolbox = base.Toolbox()
# toolbox.register("attr_float", np.random.uniform, 0, 10) # 设置初始值范围
# toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_float, n=6)   # 设置个体长度为6
# toolbox.register("population", tools.initRepeat, list, toolbox.individual)
# 
# toolbox.register("mate", tools.cxBlend, alpha=0.5)
# toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=2, indpb=0.2)
# toolbox.register("select", tools.selTournament, tournsize=3)
# toolbox.register("evaluate", objective_function, x=data, y=data_obs)
# 
# # 设置并行计算
# import multiprocessing
# pool = multiprocessing.Pool()
# toolbox.register("map", pool.map)
# 
# population = toolbox.population(n=50) # 减少种群大小,300
# ngen, cxpb, mutpb = 10, 0.5, 0.2 # 减少迭代次数,50
# 
# # 添加边界限制
# def checkBounds(min_val, max_val):
#     def decorator(func):
#         def wrapper(*args, **kwargs):
#             offspring = func(*args, **kwargs)
#             for child in offspring:
#                 for i in range(len(child)):
#                     if child[i] < min_val[i]:
#                         child[i] = min_val[i]
#                     elif child[i] > max_val[i]:
#                         child[i] = max_val[i]
#             return offspring
#         return wrapper
#     return decorator
# 
# min_val = [0, 0, 0, 0, 0, 0]
# max_val = [10, 10, 10, 10, 10, 10]
# 
# toolbox.decorate("mate", checkBounds(min_val, max_val))
# toolbox.decorate("mutate", checkBounds(min_val, max_val))
# 
# # 设置统计信息
# stats = tools.Statistics(lambda ind: ind.fitness.values)
# # stats.register("min", np.min)
# stats.register("max", np.max)  # 修改统计信息为最大值
# stats.register("avg", np.mean)
# 
# # 日志记录
# logbook = tools.Logbook()
# logbook.header = ["gen", "nevals"] + stats.fields
# 
# 
# # 定义进化过程
# def eaSimpleVerbose(population, toolbox, cxpb, mutpb, ngen, stats=None, halloffame=None, verbose=False):
#     logbook = tools.Logbook()
#     logbook.header = ['gen', 'nevals'] + (stats.fields if stats else [])
# 
#     if halloffame is not None:
#         halloffame.update(population)
# 
#     # 确保初始种群中有有效的个体
#     invalid_ind = [ind for ind in population if not ind.fitness.valid]
#     if invalid_ind:
#         fitnesses = list(toolbox.map(toolbox.evaluate, invalid_ind))
#         for ind, fit in zip(invalid_ind, fitnesses):
#             ind.fitness.values = fit
# 
#     record = stats.compile(population) if stats else {}
#     logbook.record(gen=0, nevals=len(population), **record)
#     if verbose:
#         print(logbook.stream)
# 
#     for gen in range(1, ngen + 1):
#         offspring = toolbox.select(population, len(population))
#         offspring = list(map(toolbox.clone, offspring))
# 
#         for child1, child2 in zip(offspring[::2], offspring[1::2]):
#             if np.random.rand() < cxpb:
#                 toolbox.mate(child1, child2)
#                 del child1.fitness.values
#                 del child2.fitness.values
# 
#         for mutant in offspring:
#             if np.random.rand() < mutpb:
#                 toolbox.mutate(mutant)
#                 del mutant.fitness.values
# 
#         invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
#         fitnesses = list(toolbox.map(toolbox.evaluate, invalid_ind))
#         for ind, fit in zip(invalid_ind, fitnesses):
#             ind.fitness.values = fit
# 
#         population[:] = offspring
# 
#         if halloffame is not None:
#             halloffame.update(population)
# 
#         # 确保种群中有有效的个体
#         valid_individuals = [ind for ind in population if ind.fitness.valid]
#         if len(valid_individuals) > 0:
#             record = stats.compile(valid_individuals) if stats else {}
#             logbook.record(gen=gen, nevals=len(invalid_ind), **record)
#             if verbose:
#                 print(logbook.stream)
# 
#             # 输出当前迭代次数和最优结果
#             best_individual = tools.selBest(population, k=1)[0]
#             print(f"Generation {gen}: Best individual = {best_individual}, Fitness = {best_individual.fitness.values[0]}")
#         else:
#             print(f"Generation {gen}: No valid individuals in population")
# 
#     return population, logbook
# 
# 
# 
# 
# # 运行遗传算法
# result, log = eaSimpleVerbose(population, toolbox, cxpb, mutpb, ngen, stats=stats, halloffame=None, verbose=True)
# 
# 
# # 关闭池
# pool.close()
# pool.join()
# 
# 
# # 关闭池
# pool.close()
# pool.join()
# 
# # 获取估计的参数
# best_individual = tools.selBest(result, k=1)[0]
# estimated_params = best_individual
# 
# 
# print(f"Estimated parameters: a1 = {estimated_params[0]}, a2 = {estimated_params[1]}, a3 = {estimated_params[2]}, \
# a4 = {estimated_params[3]}, a5 = {estimated_params[4]}, a6 = {estimated_params[5]}")
# =============================================================================
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

balabalahoo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值