曲线拟合

# 使用非线性最小二乘法拟合
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np

# 用指数形式来拟合
y = np.array([0.45, 0.49, 0.40, 0.52, 0.57, 0.62, 0.64, 0.66, 0.52, 0.50, 0.43, 0.20, 0.14, 0.13,0.11 ])
x = np.array([i / 10 for i in range(70, 100, 2)])
print(x.shape)
print(y.shape)

z1 = np.polyfit(x, y, 6)#用 N 次多项式拟合
p1 = np.poly1d(z1)
print(p1) #在屏幕上打印拟合多项式
yvals=p1(x)#也可以使用 yvals=np.polyval(z1,x)
plot1=plt.plot(x, y, '*',label='F1 score')
plot2=plt.plot(x, yvals, 'r',label='trend F1 score')
plt.xlabel('m')
plt.ylabel('F1 score')
plt.legend(loc=1)#指定 legend 的位置,读者可以自己 help 它的用法
plt.title('m - F1 score')
plt.show()

# def func(x, a, b):
#     return a * np.exp(b / x)
#
# def f_gauss(x, A, B, C=1, sigma=1):
#   return A*np.exp(-(x-B)**2/(2*sigma**2)) + C
#
# popt, pcov = curve_fit(f_gauss, x, y)
# a = popt[0]  # popt里面是拟合系数,读者可以自己help其用法
# b = popt[1]
# yvals = func(x, a, b)
# plot1 = plt.plot(x, y, label='original values')
# plot2 = plt.plot(x, yvals, label='curve_fit values')
# plt.xlabel('x axis')
# plt.ylabel('y axis')
# plt.legend()  #loc=4 指定legend的位置,读者可以自己help它的用法
# plt.title('curve_fit')
# plt.show()
# #plt.savefig('p2.png')

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容