拟合曲线
多项式拟合
np.ployfit(x, y, deg)
import matplotlib.pyplot as plt
import numpy as np
x = [1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8]
y = [33.40, 79.50, 122.65, 159.05, 189.15, 214.15, 238.65, 252.2, 267.55, 280.50, 296.65, 301.65, 310.4, 318.15, 325.15]
coef = np.polyfit(x, y, 2) # 返回拟合参数
fn = np.poly1d(coef) # 利用参数生成多项式函数
plt.scatter(x, y)
plt.plot(x, fn(x), color='red')
plt.show()
任意拟合
scipy.optimize.curve_fit
import scipy.optimize as opt
from scipy.optimize import curve_fit
# 已有数据点
x = np.array([1, 2, 3, 4, 5])
y = np.array([1, 4, 9, 16, 25])
# 定义拟合方程(任意)
def func(x1, a, b, c):
return a*x1**2 + b*x1 + c
p_opt, p_cov = curve_fit(func, x, y) # p0 = 1是因为只有a一参数
print("方程参数最佳值为:", p_opt.astype(np.int64)) # 参数最佳值,np.round(popt, 4)
print("拟合方程协方差矩阵:\n", p_cov) # 协方差矩阵,popt[0],popt[1],popt[2]分别代表参数a b c
y_predict = func(x, p_opt[0], p_opt[1], p_opt[2])
plt.scatter(x, y, marker='x', lw=1, label='原始数据')
plt.plot(x, y_predict, c='r', label='拟合曲线')
plt.legend() # 显示label
plt.show()
标签:opt,plt,Python,曲线,popt,拟合,np,import
From: https://www.cnblogs.com/dearmyheart/p/18329884