Moving Average
移动平均算法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 stats def 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 = 5
mode = '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 ma def raw_data():
start_ts = 1533204000
stop_ts = 1533222000
url = '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_lst def run(downloadspeed_lst):
downloadspeed_ndarray = np.array(downloadspeed_lst)
ma = moving_average(downloadspeed_ndarray)
return ma data = 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()
执行结果:

蓝色是原始数据,棕色是经过移动平均算法弱化后的数据。
2018-08-07 补充
import numpy as np
from matplotlib import pyplot as plt def moving_average(array, window=3):
N = window
n=np.ones(N)
weights=n/N
sma=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
Moving Average的更多相关文章
- [LeetCode] Moving Average from Data Stream 从数据流中移动平均值
Given a stream of integers and a window size, calculate the moving average of all integers in the sl ...
- Moving Average from Data Stream
Given a stream of integers and a window size, calculate the moving average of all integers in the sl ...
- LeetCode Moving Average from Data Stream
原题链接在这里:https://leetcode.com/problems/moving-average-from-data-stream/ 题目: Given a stream of integer ...
- EMA计算的C#实现(c# Exponential Moving Average (EMA) indicator )
原来国外有个源码(TechnicalAnalysisEngine src 1.25)内部对EMA的计算是: var copyInputValues = input.ToList(); for (int ...
- LeetCode 346. Moving Average from Data Stream (数据流动中的移动平均值)$
Given a stream of integers and a window size, calculate the moving average of all integers in the sl ...
- 理解滑动平均(exponential moving average)
1. 用滑动平均估计局部均值 滑动平均(exponential moving average),或者叫做指数加权平均(exponentially weighted moving average),可以 ...
- [Swift]LeetCode346. 从数据流中移动平均值 $ Moving Average from Data Stream
Given a stream of integers and a window size, calculate the moving average of all integers in the sl ...
- tensorflow中moving average的用法
一般在保存模型参数的时候,都会保存一份moving average,是取了不同迭代次数模型的移动平均,移动平均后的模型往往在性能上会比最后一次迭代保存的模型要好一些. tensorflow-model ...
- Moving Average from Data Stream LT346
Given a stream of integers and a window size, calculate the moving average of all integers in the sl ...
- [leetcode]346. Moving Average from Data Stream滑动窗口平均值
Given a stream of integers and a window size, calculate the moving average of all integers in the sl ...
随机推荐
- UVALive - 3523 - Knights of the Round Table
Problem UVALive - 3523 - Knights of the Round Table Time Limit: 4500 mSec Problem Description Input ...
- 8-过滤器Filter和监听器Listener
一.web监听器:监听特殊事件的发生1.监听实现步骤 a.写一个java类,实现特定的接口,重写相关方法 b.在web.xml中,牌配置 <listener> <listener-c ...
- mysql中group by和order by混用 结果不是理想结果(转)
文章转自 https://www.cnblogs.com/myphper/p/3767572.html 在使用mysql排序的时候会想到按照降序分组来获得一组数据,而使用order by往往得到的不是 ...
- Centos7.x做开机启动脚本
cat /etc/centos-release CentOS Linux release 7.4.1708 (Core) uname -r 3.10.0-693.11.1.el7.x86_64 vim ...
- uiautomator2 使用Python测试 Android应用
GitHub地址:https://github.com/openatx/uiautomator2 介绍 uiautomator2 是一个可以使用Python对Android设备进行UI自动化的库.其底 ...
- wince单实例启动
static class Program { [DllImport("Toolhelp.dll")] public static extern IntPtr CreateToolh ...
- ReentrantLock重入锁详解
1.定义 重入锁:能够支持一个线程对资源的重复加锁,也就是当一个线程获取到锁后,再次获取该锁时而不会被阻塞. 2.可重入锁的应用场景 2.1 如果已经加锁,则不再重复加锁,比如:交互界面点击后响应时间 ...
- python dlib opencv 人脸68点特征检测
不得不感慨,现在现成的东西太多了,直接拿来用就行了 dlib安装(指定版本安装,避免踩坑) pip dlib中训练好的文件http://dlib.net/files/shape_predictor_6 ...
- J2SE学习笔记
如何学习Java 一.面向对象设计思想 1.面向对象:开车去新疆,车怎么去的我不管,我只调用车的go() 方法即可. 2.类和对象:类可以看成一类对象的模板,对象可以看成该类的一个具体实例. 3.类和 ...
- U盘文件被隐藏
转自https://blog.csdn.net/zichen_ziqi/article/details/80171891 文章原地址:http://www.uqidong.com/help/1625. ...