加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

在python中用遗传算法做曲线拟合

(2012-02-22 23:00:36)
标签:

python

遗传算法

曲线拟合

非线性拟合

ic50

4pl


import sys, math
from pyevolve import G1DList, GSimpleGA, Selectors, Scaling, DBAdapters
#------------------------------------------------------------------
# 从文件中读取数据
ifile = open( 'mydata.txt', 'r')
linedata = ()
mypoints = []
for line in ifile:
  pair = line.split()   
  linedata = (float(pair[0]), float(pair[1]))
  mypoints.append(linedata)
#------------------------------------------------------------------
#定义你要拟合的曲线方程,例如 y = a*x + b
def eval_curve(concentration, a, b):
  activity = a*concentration + b
  return activity
# 定义适应度函数
def generate_fitness_function(mypoints):
  def fitness_function(chromosome):
    score = 0.0
    for point in mypoints:
      delta = abs(eval_curve(point[0], *chromosome) - point[1])
      score += delta
    score = -score
    return score
  return fitness_function
#------------------------------------------------------------------
# Create the population
genome = G1DList.G1DList(2)
genome.evaluator.set(generate_fitness_function(mypoints))
genome.setParams(rangemin=-50, rangemax=50)
# Set up the engine
ga = GSimpleGA.GSimpleGA(genome) ga.setPopulationSize(1000)
ga.selector.set(Selectors.GRouletteWheel)
# Change the scaling method
pop = ga.getPopulation() pop.scaleMethod.set(Scaling.SigmaTruncScaling)
#------------------------------------------------------------------
# Start the algorithm, and print the results.
ga.evolve(freq_stats=10)
print(ga.bestIndividual())
print("Mypoints: " + repr(mypoints))
ifile.close


其实很多的软件中都能实现曲线拟合了,尤其是非线性拟合,例如
————————————————————————————
软件                          |算法
Enzfitter (Biosoft)             |Levenberg-Marquardt; Simplex
Excel (Microsoft)              |Simplex
Fig. P (Biosoft)                 |Levenberg-Marquardt
Kaleidagraph (Synergy)   | Levenberg-Marquardt
KELL (Biosoft)                  | Levenberg-Marquardt
Origin (Microcal)               | Levenberg-Marquardt
Prism (GraphPad)             | Levenberg-Marquardt
ProFit (QuantumSoft)       | Levenberg-Marquardt; Robust; Monte Carlo (Simplex)
Scientist (Micromath)        |Levenberg-Marquardt; Simplex
SigmaPlot (SPSS)             |Levenberg-Marquardt
————————————————————————————
不知道Levenberg-Marquardt的收敛性如何,既然大多数商业性软件都可以用,应该没问题,也没有做过测试,反而对遗传算法,从全局搜索的比较感兴趣,也不会陷入局部最小。在LibreOffice里Solver有遗传算法的插件,也可以用于非线性拟合。个人认为,软件不重要,不用非钟情于Origin或者Prism,很多开源软件一样做的不错,例如Qtiplot等,关键是要知道你要拟合什么样的方程,代表什么意义。有人说Origin做图好看,只要是矢量图,应该都差不多。
    最近又对交叉熵算法感兴趣了,可是一直没有找到合适的代码。唉,学生物的做数学,那叫一个悲催阿。。。

参考: http://acodersmusings.blogspot.com/2009/07/curve-fitting-with-pyevolve.html
语法高亮显示来源于vim,语法缩进因不明原因丢失

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有