scipy.optimize.curve_fit不适用于某些功能

时间:2016-10-11 20:15:02

标签: python scipy mathematical-optimization curve-fitting

我尝试使用scipy.optimize包中的curve_fit函数来拟合一组模拟数据,以找到CoFeB的居里温度。但是,我所尝试的并不适合数据。函数(下面代码中的curie_func)应该可以工作,我已经测试过它用真实值作为初始参数(p0)进行绘制,以证明它非常合适。我得到的拟合参数是curve_fit的输出 array([ nan, nan]) 协方差矩阵是:

array([[ inf,  inf],[ inf,  inf]])

以下是演示curve_fit函数拟合随机数据(抛物线)并且不适合模拟数据的代码。

import matplotlib.pyplot as plt
import scipy.optimize as opt
import numpy as np
import random as rd

def func(x,Tc,B):
    return Tc*(x**2)+B

x = np.array([i for i in np.arange(-100,100,10)])
y = np.array([func(i,0.1,64)+rd.gauss(0,50) for i in x])

popt1 = opt.curve_fit(func,x[:-5],y[:-5])

fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.plot(x,y,'k.')

curve_fit_x = np.arange(min(x),max(x),0.1)
curve_fit_y = [func(i,*popt1[0]) for i in curve_fit_x]

ax1.plot(list(curve_fit_x),list(curve_fit_y),'b')


x  =['0', '40', '80', '120', '160', '200', '240', '280', '320', '360', '400', '440', '480', '520', '560', '600', '640', '680', '720', '760', '800', '840', '880', '920', '960', '1000', '1040', '1080', '1120', '1160', '1200', '1240', '1280', '1320', '1360', '1400']
y = ['1', '0.983289', '0.965702', '0.946315', '0.933125', '0.905639', '0.890218', '0.871013', '0.853052', '0.841008', '0.796679', '0.783795', '0.746877', '0.720693', '0.715963', '0.702506', '0.654126', '0.593997', '0.595407', '0.552495', '0.524943', '0.481418', '0.425329', '0.378469', '0.360465', '0.247084', '0.197054', '0.121997', '0.0450571', '0.0513379', '0.0572443', '0.00990522', '0.0319629', '0.0105687', '0.0173795', '0.0322641']

x = np.array([int(i) for i in x])
y = np.array([float(i) for i in y])

def curie_func(x,Tc,B):
    return (1-(x/Tc))**B


ax2 = fig.add_subplot(212)

popt2 = opt.curve_fit(curie_func,x[:-5],y[:-5])
ax2.plot(x,y,'k.')

curve_fit_x = np.arange(min(x),max(x),0.1)
curve_fit_y = [curie_func(i,*popt2[0]) for i in curve_fit_x]

ax2.plot(list(curve_fit_x),list(curve_fit_y),'b')

plt.show()

当我在p0=(1150,0.57)函数中使用参数curve_fit时,它根本不优化参数,只是将初始参数输出回控制台。下图显示curve_fit功能不起作用(底部图形)和工作(顶部图形)。

Curve_fit function not working

第二张图片说明curie_temp函数是数据的正确函数,如果curve_fit有效,它将适合它。

The curie_temp function is correct, but the curve_fit won't optimise the parameters

*编辑:运行时输出的错误(带初始参数)为:

RuntimeWarning:电源遇到无效值   return(-1+(x / Tc))** B

无法估计参数的协方差   类别= OptimizeWarning)

RuntimeWarning:在double_scalars中遇到零除   return(-1+(x / Tc))** B

RuntimeWarning:double_scalars中遇到无效值   return(-1+(x / Tc))** B

0 个答案:

没有答案