python中曲线拟合:
一个是numpy中的polyfit()函数,多项式拟合,给定变量x、y、多项式次数,返回值为多项式的一维系数array;
另一个是scipy的 optimize 模块中的 curve_fit()函数,可由自己定义拟合函数,更通用;给定变量x、y、拟合函数,返回值有两个,popt是拟合函数中的一维参数array, pcov为拟合函数中参数的 协方差array ;
二者都是基于最小二乘法;
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Email : todo@todo.todo
@Software: PyCharm
@desc :
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize
motor_instruct = [
0,
20,
40,
60,
80,
100,
120,
140,
160,
180,
200,
240,
280,
320,
360,
400,
440,
480,
520,
560,
600,
640,
680,
720,
760,
800,
840,
880,
900,
920,
940,
960,
980,
1000,
1020
]
angle_40 = [
0,
0,
5.4,
10.98,
17.28,
23.4,
29.52,
35.82,
41.58,
47.34,
53.64,
66.06,
78.48,
91.08,
102.78,
115.38,
127.98,
140.04,
151.92,
163.44,
174.78,
187.56,
200.16,
212.76,
225,
238.5,
252.36,
265.5,
272.52,
279.36,
286.56,
292.5,
298.62,
304.92,
306.18
]
angle_212_5 = [
0,
0,
4.68,
10.08,
15.3,
20.88,
27,
33.3,
40.14,
47.52,
54.54,
69.84,
85.14,
100.44,
115.56,
129.96,
144,
155.16,
165.96,
177.48,
190.44,
204.66,
220.32,
236.16,
251.1,
265.68,
278.1,
290.34,
295.56,
300.6,
306,
311.4,
316.62,
321.84,
322.74
]
angle_212_15 = [
0,
0,
5.4,
11.16,
16.38,
21.96,
27.54,
33.3,
39.78,
46.08,
52.38,
67.68,
83.52,
98.1,
112.68,
126.36,
138.96,
150.3,
161.28,
172.62,
184.68,
198,
212.76,
227.88,
243.54,
259.38,
273.6,
287.82,
293.4,
299.16,
304.92,
309.96,
316.26,
321.48,
322.56
]
def poly_fit(x, y, exponential_number=1):
f1 = np.polyfit(x[1:len(x)-1], y[1:len(y)-1], exponential_number)
print('f1 is :\n', f1)
yvals = np.polyval(f1, x[1:len(x)-1])
print('yvals is :\n', yvals)
# 绘图
plot1 = plt.plot(x[1:len(x)-1], y[1:len(y)-1], 's', label='original values')
plot2 = plt.plot(x[1:len(x)-1], yvals, 'r', label='polyfit values')
plt.xlabel('x')
plt.ylabel('y')
plt.legend(loc=4) # 指定legend的位置右下角
plt.title('polyfitting')
plt.show()
def fit_function(x, a, b):
return [a * i + b for i in x ]
def curve_fit(x, y):
popt, pcov = optimize.curve_fit(fit_function, x[1:len(x)-1], y[1:len(y)-1])
# 获取popt里面是拟合系数
print "popt >> ", popt
a = popt[0]
b = popt[1]
print "协方差矩阵 pcov >> ", pcov
yvals = fit_function(x[1:len(x) - 1], a, b)
print('yvals is :\n', yvals)
# 绘图
plot1 = plt.plot(x[1:len(x) - 1], y[1:len(y) - 1], 's', label='original values')
plot2 = plt.plot(x[1:len(x) - 1], yvals, 'r', label='polyfit values')
plt.xlabel('x')
plt.ylabel('y')
plt.legend(loc=4) # 指定legend的位置右下角
plt.title('curve_fitting')
plt.show()
if __name__=="__main__":
# poly_fit(motor_instruct, angle_212_15)
curve_fit(motor_instruct, angle_212_15)
以上两个函数可达到同样目的,都是对数据进行一次函数拟合;