资源简介
解决的例子y=10*sin(5x)+7*cos(4x)
代码用python3.6可以运行
代码片段和文件信息
# -*- coding: utf-8 -*-
“““
Created on Sat Mar 30 17:01:13 2019
@author: Administrator
“““
import random
import math
import numpy as np
import matplotlib.pyplot as plt
population_size = 500 # 种群数量
generations = 200 # 迭代次数
chrom_length = 10 # 染色体长度
pc = 0.6 # 交配概率
pm = 0.01 # 变异概率
genetic_population = [] # 种群的基因编码(二进制)
population = [] # 种群对应的十进制数值并标准化范围到[0 10]
fitness = [] # 适应度
fitness_mean = []
optimum_solution = [] # 每次迭代的所获得的最优解
# 为染色体进行01编码,生成初始种群
def chrom_encoding():
for i in range(population_size):
population_i = []
for j in range(chrom_length):
population_i.append(random.randint(0 1))
genetic_population.append(population_i)
# 对染色体进行解码,将二进制转化为十进制
def chrom_decoding():
population.clear()
for i in range(population_size):
value = 0
for j in range(chrom_length):
value += genetic_population[i][j] * (2 ** (chrom_length - 1 - j))
population.append(value * 10 / (2 ** (chrom_length) - 1))
# 计算每个染色体的适应度
def calculate_fitness():
sum = 0.0
fitness.clear()
for i in range(population_size):
function_value = 10 * math.sin(5 * population[i]) + 7 * math.cos(4 * population[i])
if function_value > 0.0:
sum += function_value
fitness.append(function_value)
else:
fitness.append(0.0)
# 返回群体的平均适应度
return sum / population_size
# 获取最大适应度的个体和对应的编号
def best_value():
max_fitness = fitness[0]
max_chrom = 0
for i in range(population_size):
if fitness[i] > max_fitness:
max_fitness = fitness[i]
max_chrom = i
return max_chrom max_fitness
# 采用轮盘赌算法进行选择过程,重新选择与种群数量相等的新种群
def selection():
fitness_proportion = []
fitness_sum = 0
for i in range(population_size):
fitness_sum += fitness[i]
# 计算生存率
for i in range(population_size):
fitness_proportion.append(fitness[i] / fitness_sum)
pie_fitness = []
cumsum = 0.0
for i in range(population_size):
pie_fitness.append(cumsum + fitness_proportion[i])
cumsum += fitness_proportion[i]
pie_fitness[-1] = 1
# 生成随机数在轮盘上选点[0 1)
random_selection = []
for i in range(population_size):
random_selection.append(random.random())
random_selection.sort()
# 选择新种群
new_genetic_population = []
random_sel
相关资源
- python实现SGBM图像匹配算法
- python实现灰度直方图均衡化
- scrapy_qunar_one
- Python学习全系列教程永久可用
- python简明教程.chm
- 抽奖大转盘python的图形化界面
- 双边滤波器实验报告及代码python
- python +MYSQL+HTML实现21蛋糕网上商城
- Python-直播答题助手自动检测出题搜索
- OpenCV入门教程+OpenCV官方教程中文版
- Python 串口工具源码+.exe文件
- Python开发的全栈股票系统.zip
- Python操作Excel表格并将其中部分数据写
- python书籍 PDF
- 利用python绘制散点图
- python+labview+No1.vi
- 老男孩python项目实战
- python源码制作whl文件.rar
- python3.5可用的scipy
- PYTHON3 经典50案例.pptx
- 计算机科学导论-python.pdf
- python模拟鼠标点击屏幕
- windows鼠标自动点击py脚本
- 鱼c小甲鱼零基础学python全套课后题和
- Python 练习题100道
- Practical Programming 2nd Edition
- wxPython Application Development Cookbook
- python 3.6
- Python 3.5.2 中文文档 互联网唯一CHM版本
- python3.5.2.chm官方文档
评论
共有 条评论