【python】scipy.optimize.curve_fit

功能

使用非线性最小平方差来拟合一个函数

功能介绍

官方文档
在这里插入图片描述
输入

参数Value
f函数,它必须以xdata为第一个入参
xdata测量的独立数据
ydata相关的数据,名义上是 f(xdata,…)的结果

输出

输出Value
popt最优值,即拟合函数根据x输出的值
pcovpopt的协方差矩阵
infodicta dictionary of optional outputs with the keys (returned only if full_output is True)
mesg相关的信息 (returned only if full_output is True)
ierAn integer flag. If it is equal to 1, 2, 3 or 4, the solution was found. Otherwise, the solution was not found. In either case, the optional output variable mesg gives more information. (returned only if full_output is True)

例子

官方的例子

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

def official_demo_func(x, a, b, c):
    return a * np.exp(-b * x) + c


def official_demo():
    x = np.linspace(0, 4, 50)
    y = official_demo_func(x, 2.5, 1.3, 0.5)
    rng = np.random.default_rng()
    y_noise = 0.2 * rng.normal(size=x.size)
    ydata = y + y_noise
    plt.plot(x, ydata, 'b-', label='data')

    popt, pcov = curve_fit(official_demo_func, x, ydata)
    print(popt)

    plt.plot(x, official_demo_func(x, *popt), 'g--',
             label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))

    plt.xlabel('x')
    plt.ylabel('y')
    plt.legend()
    plt.show()


official_demo()

在这里插入图片描述
输出拟合结果为

[2.61499295 1.35033395 0.51541771]

它与输入的值 [2.5, 1.3, 0.5],还是很相近的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值