使用numpy拟合预测趋势

实现

代码

#Header
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

#Define a function(here a exponential function is used)
def func(x, a, b, c):
 return a * np.exp(b * x) + c

fo = open("data.txt", 'r')
xdata = list()
ydata = list()
entry = fo.readline()
#start_year = 1982
offset = 0
while entry:
    offset += 1
    lt = entry.split('\t')
    data = lt[1]
    data = data.rstrip('\n') #data format 1982\t203\n
    xdata.append(offset)
    ydata.append(int(data))
    entry = fo.readline()
xdata = np.array(xdata)
ydata = np.array(ydata)
plt.plot(xdata, ydata, 'bo', label='data') #mark the scatter

#Fit for the parameters a, b, c of the function func:
popt, pcov = curve_fit(func, xdata, ydata)
popt #output: array([ 2.55423706, 1.35190947, 0.47450618])
xrge = list()
for i in range(2050-1982):
    xrge.append(i) #draw the curve until 2050
xrge = np.array(xrge)
plt.plot(xrge, func(xrge, *popt), 'r-',
 label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))

#Labels
plt.title("Exponential Function Fitting")
#fc-list :lang=zh-cn Ubuntu命令行查看已安装字体
zhfont = mpl.font_manager.FontProperties(fname='/usr/share/fonts/opentype/noto/NotoSerifCJK-Bold.ttc')
plt.xlabel('年份', fontproperties=zhfont)
plt.ylabel('average GDP')
plt.legend()
leg = plt.legend()  # remove the frame of Legend, personal choice
leg.get_frame().set_linewidth(0.0) # remove the frame of Legend, personal choice

#Export figure
plt.savefig('fit1.jpg', format='jpg', dpi=1000, facecolor='w', edgecolor='k')

结果图例

中国人均GDP预测

数据2

1982	203
1983	225
1984	250
1985	294
1986	281
1987	251
1988	283
1989	310
1990	317
1991	333
1992	366
1993	377
1994	473
1995	609
1996	709
1997	781
1998	828
1999	873
2000	959
2001	1053
2002	1148 
2003	1288
2004	1508
2005	1753
2006	2099
2007	2693
2008	3468
2009	3832
2010	4550
2011	5618
2012	6316
2013	7050
2014	7678
2015	8066
2016	8147
2017	8879
2018	9976
2019	10216
2020	10500

Tips

#在start与stop之间生成均匀的num个数据,作为array返回
numpy.linspace(start, stop, num)

#为np随机数生成器插入种子
numpy.random.seed(1111)

#返回size维array,每维X~N(loc, scale^2)
np.random.normal(loc, scale, size)

#拟合参数有限制范围,使用二元tuple,每元可使用列表,假定共3参数
popt, pcov = curve_fit(func, xdata, ydata, bounds=(0, [a, b, c]))

代码主体参考:图様, “使用python做数据拟合”, zhuanlan.zhihu

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值