如何在Python中进行曲线拟合

1 投票
1 回答
568 浏览
提问于 2025-04-18 02:59

我需要用一个公式 y = x / (a + x) 来拟合一组数据,其中 a 是我需要从这个练习中得到的参数。

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

x = [1, 2, 7, 10, 20, 70, 200, 1000]
y = [0, 0, 15.3, 34.6, 49.3, 82.6, 100]
def fit(x, a):
    return x/(a+x)
par, con = curve_fit(fit, x, y)
plt.plot(x, fit(x, par[0]))
plt.show()

用这个公式我得到的结果很糟糕,根本不符合数据。

如果我这样尝试:

def fit(x, a, b):
    return b*x/(a+x)

我得到了一个拟合结果,但没有圆角,看起来就是直线。我到底哪里做错了呢?

1 个回答

3

注意你的 x 是一个 int 类型的 list,在 Python 中,除法默认是整数除法,这里并不是你想要的结果。

所以,做一些小改动就能让它正常工作,以第二个函数为例,你的第一个函数不太合适,因为当 x 趋近于无穷大时,它的结果会限制在1:

def fit(x, a, b):
    return b*x*1./(a+x)
A, B=curve_fit(fit, x, y)[0]
plt.plot(x, fit(x, A, B))
plt.plot(x, y, 'r+')
plt.savefig('temp.png')

enter image description here

这是一些直线,因为你只在那些 x 值上计算 y。如果想要得到曲线,可以把绘图的调用改成 plt.plot(np.linspace(0,200,100), fit(np.linspace(0,200,100), A, B))

enter image description here

撰写回答