首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >curve_fit返回初始参数估计

curve_fit返回初始参数估计
EN

Stack Overflow用户
提问于 2013-07-30 17:39:18
回答 1查看 2K关注 0票数 2

我正在尝试使用fit curve_fit来拟合我的数据的高斯函数,在网络上有很多有用的例子,我试着让几个工作,但没有结果。我用虚构的数据编写了一个简单的脚本来诊断问题。简而言之,curve_fit没有做任何拟合,函数只是返回初始参数值,不管它们离实数有多近。下面是简单脚本的代码:

代码语言:javascript
复制
# -*- 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

我尝试过的东西:-using最不直接:同样的问题,-reinstalling参与:没有改变

我在Windows 7上使用Anaconda。

有什么问题吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-31 00:06:18

您对f()的定义是奇怪的,并不能做您想做的事情。您将mb分配给p,从而覆盖传入的任何内容。这就是为什么参数永远不会改变的原因,因为它们不会改变!

没有必要以一种特殊的方式来定义f(),只需按照通常的方式定义参数就可以了。对于您简单的拟合线的情况,我们可以使用

代码语言:javascript
复制
def f(x, m, b) :
    return m*x + b

唯一需要的其他改变是

代码语言:javascript
复制
Initial_model = f(datax, *p_init)

你的代码就会运行。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17953735

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档