2013-07-30 56 views
2

我想使用scipy curve_fit来适合我的数据高斯函数,在网上有很多有用的例子,我试图让几个工作,但无济于事。我用一个简单的脚本编写了数据来诊断问题。简而言之,curve_fit没有做任何拟合,该函数只是返回初始参数值,而不管它们与实数有多接近。下面是简单的脚本代码:scipy curve_fit返回初始参数估计

# -*- coding: utf-8 -*- 
import numpy 
import matplotlib.pyplot as plt 
import matplotlib.mlab as mlab 
from scipy import optimize 

##Fit 
def Fit(datax, datay):  
    # define your function: 
    def f(x, *p): 
     p = m, b  
     return m*numpy.asarray(x) + b 
    m = 0.4 
    b = 2.4 
    p_init = [m, b] 
    Initial_model = f(datax, [m, b])  
    plt.plot(datax, Initial_model, label='Initial Model') 
    plt.title("Initial Model") 
# plt.title('Initial Model') 
# plt.show() 
    # fit! (given that data is an array with the data to fit) 
    print optimize.curve_fit(f, datax, datay, p_init) 
    coeff, var_matrix = optimize.curve_fit(f, datax, datay, p_init) 
    global fit 
    fit = f(datax, *coeff) 
    plt.plot(datax, fit, 'r-') 
    plt.show() 
    print 'Fitted slope 1 = ', coeff[0] 
    print 'Fitted intercept 1 = ', coeff[1] 
    return fit 

##Plot 
def Plot(datax, datay, fit): 
    fig = plt.figure() 
    ax = fig.add_subplot(111) 
    plt.plot(datax, datay, 'b*') 
    l = ax.plot(datax, fit, 'r-', linewidth=2) 
    ax.set_xlabel('Rate') 
    ax.set_ylabel('Return') 
    ax.set_title("Test") 
    ax.autoscale(enable=True, axis='both', tight=None) 
    ax.grid(True) 
    plt.show() 

##data 
datax = numpy.array([7.02, 20.06, 13.78, 16.92, 10.17], dtype=numpy.float64) 
datay = numpy.array([5.14, 10.66, 8.44, 9.64, 6.79], dtype=numpy.float64) 

##analyze 
Fit(datax, datay) 
Plot(datax, datay, fit) 

Out: 
(array([ 0.4, 2.4]), inf) 
Fitted slope 1 = 0.4 
Fitted intercept 1 = 2.4 

事情我已经尝试: leastsq直接 - 使用:同样的问题 -reinstalling SciPy的:没有变化

我使用蟒蛇在Windows 7

可能是什么问题?

+0

什么情况是你给你的数据增加了噪音,并改变了初始猜测值,所以它不再与实际参数相同? –

回答

3

你对f()的定义是奇特的,并没有做你想做的。您正在将mb分配到p,从而覆盖所有传入的内容。这就是为什么参数永远不会更改,因为它们不会更改!

有没有必要以一种特殊的方式定义f(),只是定义它是有意义的列出参数的方式,就像你通常会。对于您的拟合线的简单情况下,我们可以使用

def f(x, m, b) : 
    return m*x + b 

唯一需要的其他变化是

Initial_model = f(datax, *p_init) 

,你的代码将运行。

相关问题