为什么scipy.optimize.curve_fit不能产生最适合我的观点的线? [英] Why does scipy.optimize.curve_fit not produce a line of best fit for my points?

查看:130
本文介绍了为什么scipy.optimize.curve_fit不能产生最适合我的观点的线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组数据点(下面的代码中的x和y),并且我试图通过这些点创建最合适的线性线.我正在使用scipy.optimize.curve_fit.我的代码产生了一行,但没有一条最合适的行.我曾尝试给函数模型参数提供用于渐变和截距的参数,但是每次它生成的行完全相同时,就不适合我的数据点.

I have a set of data points, (x and y in the code below) and I am trying to create a linear line of best fit through my points. I am using scipy.optimize.curve_fit. My code produces a line, but not a line of best fit. I have tried giving the function model parameters to use for my gradient and for my intercept, but each time it produces the exact same line which does not fit to my data points.

蓝点是我的数据点,红线应该适合:

The blue dots are my data points the red line should be fitted to:

如果有人可以指出我要去哪里,我将非常感激:

If anyone could point out where I am going wrong I would be extremely grateful:

import numpy as np
import matplotlib.pyplot as mpl
import scipy as sp
import scipy.optimize as opt

x=[1.0,2.5,3.5,4.0,1.1,1.8,2.2,3.7]
y=[6.008,15.722,27.130,33.772,5.257,9.549,11.098,28.828]
trialX = np.linspace(1.0,4.0,1000)                         #Trial values of x

def f(x,m,c):                                        #Defining the function y(x)=(m*x)+c
    return (x*m)+c

popt,pcov=opt.curve_fit(f,x,y)                       #Returning popt and pcov
ynew=f(trialX,*popt)                                                  

mpl.plot(x,y,'bo')
mpl.plot(trialX,ynew,'r-')
mpl.show()

推荐答案

您也可以使用numpy.polyfit获得最合适的行:

You could alternatively use numpy.polyfit to get the line of best fit:

import numpy as np
import matplotlib.pyplot as mpl

x=[1.0,2.5,3.5,4.0,1.1,1.8,2.2,3.7]
y=[6.008,15.722,27.130,33.772,5.257,9.549,11.098,28.828]
trialX = np.linspace(1.0,4.0,1000)                         #Trial values of x

#get the first order coefficients 
fit = np.polyfit(x, y, 1)

#apply 
ynew = trialX * fit[0] + fit[1]                                              

mpl.plot(x,y,'bo')
mpl.plot(trialX,ynew,'r-')
mpl.show()

以下是输出:

这篇关于为什么scipy.optimize.curve_fit不能产生最适合我的观点的线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆