## 【Python】python曲线拟合

Yngz_Miao 2020-11-13 07:51:29
Python 曲线 曲线拟合 拟合

python作为一款可以简单方便地进行科学计算的语言，进行曲线拟合自然是必备的功能之一了。本文就如何进行曲线拟合进行讲解。

``````x = np.arange(1, 31, 1)
y = np.array([20, 23, 26, 29, 32, 35, 38, 45, 53, 62, 73, 86, 101, 118, 138, 161, 188, 220, 257, 300, 350, 409, 478, 558, 651, 760, 887, 1035, 1208, 1410])
``````

## 多项式拟合

``````def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):
"""
Least squares polynomial fit.
Fit a polynomial ``p(x) = p[0] * x**deg + ... + p[deg]`` of degree `deg`
to points `(x, y)`. Returns a vector of coefficients `p` that minimises
the squared error.
``````

``````# coding=utf-8
import pylab
import numpy as np
if __name__ == "__main__":
x = np.arange(1, 31, 1)
y = np.array([20, 23, 26, 29, 32, 35, 38, 45, 53, 62, 73, 86, 101, 118, 138, 161, 188, 220, 257, 300, 350, 409, 478, 558, 651, 760, 887, 1035, 1208, 1410])
z1 = np.polyfit(x, y, 3) # 曲线拟合，返回值为多项式的各项系数
p1 = np.poly1d(z1) # 返回值为多项式的表达式，也就是函数式子
print(p1)
y_pred = p1(x) # 根据函数的多项式表达式，求解 y
# print(np.polyval(p1, 29)) 根据多项式求解特定 x 对应的 y 值
# print(np.polyval(z1, 29)) 根据多项式求解特定 x 对应的 y 值
plot1 = pylab.plot(x, y, '*', label='original values')
plot2 = pylab.plot(x, y_pred, 'r', label='fit values')
pylab.title('')
pylab.xlabel('')
pylab.ylabel('')
pylab.show()
pylab.savefig('p1.png', dpi=200, bbox_inches='tight')
``````

``````[email protected]:~/test/blog\$ python nihe.py
3 2
0.1215 x - 3.045 x + 28.62 x - 34.47
``````

## 非多项式拟合

``````def func(x, a, b, c):
return b * np.power(a, x) + c
``````

``````# coding=utf-8
import pylab
import numpy as np
import sys, os
from scipy.optimize import curve_fit
def func(x, a, b, c):
return b * np.power(a, x) + c
if __name__ == "__main__":
x = np.arange(1, 31, 1)
y = np.array([20, 23, 26, 29, 32, 35, 38, 45, 53, 62, 73, 86, 101, 118, 138, 161, 188, 220, 257, 300, 350, 409, 478, 558, 651, 760, 887, 1035, 1208, 1410])
popt, pcov = curve_fit(func, x, y) # 曲线拟合，popt为函数的参数list
y_pred = [func(i, popt[0], popt[1], popt[2]) for i in x] # 直接用函数和函数参数list来进行y值的计算
print(popt)
plot1 = pylab.plot(x, y, '*', label='original values')
plot2 = pylab.plot(x, y_pred, 'r', label='fit values')
pylab.title('')
pylab.xlabel('')
pylab.ylabel('')
pylab.show()
pylab.savefig('p1.png', dpi=200, bbox_inches='tight')
``````

``````[email protected]:~/test/blog\$ python nihe.py
[ 1.16791847 13.39168895 1.24633734]
``````

## 相关阅读

https://yngzmiao.blog.csdn.net/article/details/105093434