使用python实现数据拟合

在这里插入代码片

import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams[‘font.family’] = [‘SimHei’]
plt.show()

示例数据

x = np.array([0.04,
0.0425,
0.0465,
0.0505,
0.0545,
0.0585,
0.0625,
0.0665,
0.0705,
0.0745,
0.0785,
0.0825,
0.0865,
0.0905,
0.0945,
0.0985,
0.1025,
0.1065,
0.1105,
0.1145,
0.1185,
0.1225,
0.1265,
0.1305,
0.1345,
0.1385,
0.1425,
0.1465,
0.15
])
y = np.array([0,
0.094574126,
0.135727183,
0.224603354,
0.302038102,
0.347315668,
0.41347177,
0.447890973,
0.497634453,
0.511096612,
0.573393087,
0.609492115,
0.652944774,
0.667541843,
0.694779921,
0.708302023,
0.731275401,
0.775091405,
0.798227368,
0.790527266,
0.815196986,
0.814421029,
0.854811097,
0.870317343,
0.871428085,
0.885925945,
0.874434682,
0.902725909,
0.922060687
])

假设我们想要找到一个更复杂的二次方程 y = ax^2 + bx + c + dsin(ex) 来拟合数据

定义函数

def func(x, a, b, c, d, e):
return a * x ** 2 + b * x + c + d * np.sin(e * x)

使用curve_fit进行曲线拟合

popt, pcov = curve_fit(func, x, y)

打印拟合参数

print(“拟合参数:”, popt)

计算拟合曲线

y_fit = func(x, *popt)

计算均方误差

mse = np.mean((y - y_fit) ** 2)
print(“均方误差:”, mse)

绘制原始数据和拟合曲线

plt.plot(x, y, ‘o’, label=‘原始数据’)
plt.plot(x, y_fit, ‘-’, label=‘拟合曲线’)
plt.xlabel(‘x’)
plt.ylabel(‘y’)
plt.title(‘复杂二次曲线拟合’)
plt.legend()

计算残差平方和(Sum of Squares of Residuals, SSR)

SSR = np.sum((y - y_fit) ** 2)

计算总平方和(Total Sum of Squares, SST)

y_mean = np.mean(y)
SST = np.sum((y - y_mean) ** 2)

计算决定系数(R-squared)

r_squared = 1 - (SSR / SST)
print(“决定系数:”, r_squared)

显示图表

plt.show()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值