使用scipy.optimize.curve_fit绘制图 [英] Plotting graph using scipy.optimize.curve_fit

查看:62
本文介绍了使用scipy.optimize.curve_fit绘制图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解 optimize.curve_fit 函数时遇到问题.我的拟合函数是幂律.但是我不知道plot命令中的第二个值应该是什么?首先我们必须调用函数 ff(L,v) 它会返回我们拟合线,但我们没有调用这个函数.我想知道该命令的工作方式.

I am having trouble in understanding the optimize.curve_fit function. My fitting function is a power law. But I don't know exactly what should be the second value in the plot command? First we have to call function ff(L,v) it will return us fitting line but we are not calling this function. How this command is working I want to know that.

x=Ls
y=Tc
#fitting function
def ff(L,v):
    return L**(-1/v)
pfit,perr=optimize.curve_fit(ff,x,y)
plt.plot(x,...)

推荐答案

plot 命令绘制 x vs y 值,所以你必须根据你定义的函数计算相应的 y 值 ff .由于 pfit 以数组形式返回,因此在调用拟合函数 ff 时必须解压缩这些值.如果你知道你有两个系数,你当然可以像 v, k = pfit 一样简单地提取它们,然后用 ff(x, v, k) 计算 y 值代码>.但是,如果稍后将拟合函数更改为 L **(-1/v)* k + a ,该怎么办?然后,您将不得不重写代码.一种更简单的方法是将其留给Python以使用 * pfit :

The plot command plots x vs y values, so you have to calculate the corresponding y-values according to your defined function ff. Since pfit is returned as an array, you have to unpack the values when you call your fit function ff. If you know, that you have two coefficients, you could of course simply extract them like v, k = pfit and calculate the y-values with ff(x, v, k). But what if you change the fit function later on to L**(-1/v) * k + a? Then you would have to rewrite your code. An easier way is to leave it to Python to unpack your coefficients with *pfit:

from scipy.optimize import curve_fit
from matplotlib import pyplot as plt
import numpy as np

#define some sample data
x = np.arange(1, 6)
y = np.asarray([100, 37, 18, 3, 1])

#fitting function with more than one parameter to fit
def ff(L, v, k):
    return L**(-1/v) * k

pfit, perr = curve_fit(ff,x,y)
print(pfit)

#plot original data
plt.plot(x, y, "ro", label = "data")
#calculate y-values
y_fit = ff(x, *pfit)
#plot fitted curve
plt.plot(x, y_fit, "b", label = "fit")
plt.legend()
plt.show()

这当然不足以令人印象深刻,拟合的曲线看起来一点也不平滑:

This is of course less than impressive, the fitted curve doesn't look smooth at all:

为了克服这个问题,我们可能希望创建一个分辨率更高的 x 值范围,并绘制此范围而不是原始 x 值数据:

To overcome this, we might want to create an x-value range with a better resolution and plot this one instead of the original x-value data:

x_fit = np.linspace(np.min(x), np.max(x), 1000)
plt.plot(x_fit, ff(x_fit, *pfit), "b", label = "fit")

现在好多了:

这篇关于使用scipy.optimize.curve_fit绘制图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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