基本思想:
选择算子:轮盘选择(roulette wheel selection)、排序选择(rank-based selection)、锦标赛选择(Tournament selection);
交叉算子:单点交叉(Single-point crossover)、k点交叉(K-point crossover)、均匀交叉(Uniform crossover)等;
变异算子:位翻转突变(Flip bit mutation)、交换突变、反转突变(Swap mutation)等。
实数编码染色体的遗传算子:用于处理解空间连续问,也即个体由实数(浮点数)组成。混合交叉、模拟二进制交叉、实数突变。选择操作不受影响
输入:

输出:
import numpy as np
def schaffer(p):
x1, x2 = p
# x=sqe(x1)+sqr(x2)
x = np.square(x1) + np.square(x2)
# 0.5+((ser(sinx)-0.5) / sqr(1.0.001)*x)
return 0.5 + (np.square(np.sin(x)) - 0.5) / np.square(1 + 0.001 * x)
from sko.GA import GA
ga = GA(func=schaffer, n_dim=2, size_pop=50, max_iter=500, prob_mut=0.001, precision=1e-7)
best_x, best_y = ga.run()
print('best_x:', best_x, '\n', 'best_y:', best_y)
# 把结果带回去测试一下
如下:
best_x: [-9.83476668e-07 -2.98023233e-08]
best_y: [8.8817842e-16]
注:最优解为最小值,若要求最大值,需要在前面加负号
import pandas as pd
import matplotlib.pyplot as plt
Y_history = pd.DataFrame(ga.all_history_Y)
fig, ax = plt.subplots(2, 1)
ax[0].plot(Y_history.index, Y_history.values, '.', color='red')
Y_history.min(axis=1).cummin().plot(kind='line')
plt.show()
如下:

在多维优化时,想让哪个变量限制为整数,就设定 precision 为 整数 即可。例如,我想让我的自定义函数 demo_func 的某些变量限制为整数+浮点数(分别是隔2个,隔1个,浮点数),那么就设定 precision=[2, 1, 1e-7]
例子如下:
from sko.GA import GA
demo_func = lambda x: (x[0] - 1) ** 2 + (x[1] - 0.05) ** 2 + x[2] ** 2
ga = GA(func=demo_func, n_dim=3, max_iter=500, lb=[-1, -1, -1], ub=[5, 1, 1], precision=[2, 1, 1e-7])
best_x, best_y = ga.run()
print('best_x:', best_x, '\n', 'best_y:', best_y)
如下:
best_x: [1.00000000e+00 0.00000000e+00 2.98023233e-08]
best_y: [0.0025]
说明:
题目:用标准遗传算法求函数f(x)=x+10sin(5x)+7cos(4x) 的最大值。
import numpy as np
# f(x)=x+10sin(5x)+7cos(4x)
def schaffer(p):
x1, x2 = p
return x2+10*np.sin(5*x1)+7*np.cos(4*x2)
from sko.GA import GA
ga = GA(func=schaffer, n_dim=2, size_pop=50, max_iter=500, prob_mut=0.001, precision=1e-7)
best_x, best_y = ga.run()
print('x最佳值:', best_x, '\n', '最大值:', -best_y)
import pandas as pd
import matplotlib.pyplot as plt
Y_history = pd.DataFrame(ga.all_history_FitV ) #每一代的适应度
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
plt.xlabel("迭代次数")
plt.ylabel("适应度")
plt.title("适应度变化")
plt.plot(Y_history.index, Y_history.values, '.', color='red')
如下:

history = pd.DataFrame(ga.all_history_Y)
plt.plot(Y_history.index, history.values, '.', color='red')
history.min().cummin().plot(kind='line')
plt.show()

以机器学习中鸢尾花的逻辑回归为例:
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
iris = load_iris()
xtrain,xtest,ytrain,ytest = train_test_split(iris['data'],iris['target'],test_size=0.2)
def func(p):
w1, w2 = p
clf = LogisticRegression(max_iter=int(w1), random_state=int(w2))
clf.fit(xtrain,ytrain)
score = clf.score(xtest,ytest)
return -score #由于这里的GA默认求得最小值,而我们想要score达到最大值,因此需要在score前加负号
ga = GA(func=func, n_dim=2, size_pop=50, max_iter=10, lb=[0, 0],ub=[3, 10],precision=1e-7)
best_x,best_y = ga.run()
print('best_x:', best_x,'\n','best_y:',best_y)
产生x和y点:
import numpy as np
import matplotlib.pyplot as plt
from sko.GA import GA
x_true = np.linspace(-1.2, 1.2, 30)
y_true = x_true ** 3 - x_true + 0.4 * np.random.rand(30)
plt.plot(x_true, y_true, 'o')
如图:

构造参差:
def f_fun(x, a, b, c, d):
# y=a*x^2+b*x+c*x+d
return a * x ** 3 + b * x ** 2 + c * x + d
def obj_fun(p):
# 四个参数,abcd
a, b, c, d = p
# 目标为残差
residuals = np.square(f_fun(x_true, a, b, c, d) - y_true).sum()
return residuals
如下:
best_x: [ 1.03756528 0.08383939 -1.02735888 0.15224675]
best_y: [0.3521411]
拟合:
y_predict = f_fun(x_true, *best_params)
fig, ax = plt.subplots()
ax.plot(x_true, y_true, 'o')
ax.plot(x_true, y_predict, '-')
plt.show()
如下:

https://scikit-opt.github.io/scikit-opt/#/zh/curve_fitting
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Pythonconditionalassignmentoperator对于这样一个简单的问题表示歉意,但是谷歌搜索||=并不是很有帮助;)Python中是否有与Ruby和Perl中的||=语句等效的语句?例如:foo="hey"foo||="what"#assignfooifit'sundefined#fooisstill"hey"bar||="yeah"#baris"yeah"另外,类似这样的东西的通用术语是什么?条件分配是我的第一个猜测,但Wikipediapage跟我想的不太一样。
什么是ruby的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht
目录一.加解密算法数字签名对称加密DES(DataEncryptionStandard)3DES(TripleDES)AES(AdvancedEncryptionStandard)RSA加密法DSA(DigitalSignatureAlgorithm)ECC(EllipticCurvesCryptography)非对称加密签名与加密过程非对称加密的应用对称加密与非对称加密的结合二.数字证书图解一.加解密算法加密简单而言就是通过一种算法将明文信息转换成密文信息,信息的的接收方能够通过密钥对密文信息进行解密获得明文信息的过程。根据加解密的密钥是否相同,算法可以分为对称加密、非对称加密、对称加密和非
华为OD机试题本篇题目:明明的随机数题目输入描述输出描述:示例1输入输出说明代码编写思路最近更新的博客华为od2023|什么是华为od,od薪资待遇,od机试题清单华为OD机试真题大全,用Python解华为机试题|机试宝典【华为OD机试】全流程解析+经验分享,题型分享,防作弊指南华为o
我想解析一个已经存在的.mid文件,改变它的乐器,例如从“acousticgrandpiano”到“violin”,然后将它保存回去或作为另一个.mid文件。根据我在文档中看到的内容,该乐器通过program_change或patch_change指令进行了更改,但我找不到任何在已经存在的MIDI文件中执行此操作的库.他们似乎都只支持从头开始创建的MIDI文件。 最佳答案 MIDIpackage会为您完成此操作,但具体方法取决于midi文件的原始内容。一个MIDI文件由一个或多个音轨组成,每个音轨是十六个channel中任何一个上的
本文主要介绍在使用Selenium进行自动化测试或者任务时,对于使用了iframe的页面,如何定位iframe中的元素文章目录场景描述解决方案具体代码场景描述当我们在使用Selenium进行自动化测试的时候,可能会遇到一些界面或者窗体是使用HTML的iframe标签进行承载的。对于iframe中的标签,如果直接查找是无法找到的,会抛出没有找到元素的异常。比如近在咫尺的例子就是,CSDN的登录窗体就是使用的iframe,大家可以尝试通过F12开发者模式查看到的tag_name,class_name,id或者xpath来定位中的页面元素,会抛出NoSuchElementException异常。解决
2022/8/4更新支持加入水印水印必须包含透明图像,并且水印图像大小要等于原图像的大小pythonconvert_image_to_video.py-f30-mwatermark.pngim_dirout.mkv2022/6/21更新让命令行参数更加易用新的命令行使用方法pythonconvert_image_to_video.py-f30im_dirout.mkvFFMPEG命令行转换一组JPG图像到视频时,是将这组图像视为MJPG流。我需要转换一组PNG图像到视频,FFMPEG就不认了。pyav内置了ffmpeg库,不需要系统带有ffmpeg工具因此我使用ffmpeg的python包装p
ValidPalindromeGivenastring,determineifitisapalindrome,consideringonlyalphanumericcharactersandignoringcases. [#125]Example:"Aman,aplan,acanal:Panama"isapalindrome."raceacar"isnotapalindrome.Haveyouconsiderthatthestringmightbeempty?Thisisagoodquestiontoaskduringaninterview.Forthepurposeofthisproblem
是否可以在PyYAML或Ruby的Psych引擎中禁用创建anchor和引用(并有效地显式列出冗余数据)?也许我在网上搜索时遗漏了一些东西,但在Psych中似乎没有太多可用的选项,而且我也无法确定PyYAML是否允许这样做.基本原理是我必须序列化一些数据并将其以可读的形式传递给一个不是真正的技术同事进行手动验证。有些数据是多余的,但我需要以最明确的方式列出它们以提高可读性(anchor和引用是提高效率的好概念,但不是人类可读性)。Ruby和Python是我选择的工具,但如果有其他一些相当简单的方法来“展开”YAML文档,它可能就可以了。 最佳答案