Moving Average
生活随笔
收集整理的這篇文章主要介紹了
Moving Average
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
移動平均算法Demo
#!/usr/bin/python2.7 # Fetch data from BD and analyse.import json import urllib import traceback import numpy as np # import pandas as pd import matplotlib.pyplot as plt #from scipy import statsdef fetch_raw_data(url):try:response = urllib.urlopen(url).read().decode('utf-8')return json.loads(response)except Exception, e:err = traceback.format_exc()print("fetch_raw_data err: {}".format(err))# 移動平均算法 def moving_average(f_t):if type(f_t) is not np.ndarray:raise TypeError\('Expected one dimensional numpy array.')if f_t.shape[1] != 1:raise IndexError\('Expected one dimensional numpy array, %d dimensions given.' % (f_t.shape[1]))f_t = f_t.flatten()window = 5mode = 'same'g_t = np.ones(int(window))/float(window)# Deal with boundaries with atleast lag/2 day window# ma = np.convolve(f_t,g_t,mode)# ma = np.convolve(f_t,g_t,mode)[window-1:-window+1]ma = np.convolve(f_t,g_t)[window-1:-window+1]return madef raw_data():start_ts = 1533204000stop_ts = 1533222000url = 'http://8.8.8.8/path/data?begin_time={}&end_time={}&type=asia'url = url.format(start_ts,stop_ts)result = fetch_raw_data(url)# downloadspeed_lst = result['result']['downloadspeed']downloadspeed_lst = result['result']['totaluploadspeed']downloadspeed_lst = [ [ele,] for ele in downloadspeed_lst ]return downloadspeed_lstdef run(downloadspeed_lst):downloadspeed_ndarray = np.array(downloadspeed_lst)ma = moving_average(downloadspeed_ndarray)return madata = raw_data() ma = run(data) t = np.arange(4, len(data)) plt.plot(t, data[4:], lw=1.0) plt.plot(t, ma, lw=1.0) plt.show()?
執(zhí)行結(jié)果:
藍(lán)色是原始數(shù)據(jù),棕色是經(jīng)過移動平均算法弱化后的數(shù)據(jù)。
?
2018-08-07 補充
import numpy as np from matplotlib import pyplot as pltdef moving_average(array, window=3):N = windown=np.ones(N)weights=n/Nsma=np.convolve(weights,array)[N-1:-N+1]t=np.arange(N-1,len(array))plt.plot(t,array[N-1:],lw=1)plt.plot(t,sma,lw=2)plt.show()return sma卷積運算
numpy.convolve(weights,array)[N-1:-N+1]weight = [a,b,c] array = [i,j,k,m,n]Result: [ai, bi+aj, ci+bj+ak, cj+bk+am, ck+bm+an, cm+bn, cn][N-1:-N+1]?
如何理解卷積運算?
?
?
參考:https://www.cnblogs.com/21207-iHome/p/6231607.html
參考:https://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html
?
轉(zhuǎn)載于:https://www.cnblogs.com/standby/p/9427384.html
總結(jié)
以上是生活随笔為你收集整理的Moving Average的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: EasyNVR、EasyDSS二次开发之
- 下一篇: protobuf java基础