移动平均算法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的更多相关文章

  1. [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 ...

  2. Moving Average from Data Stream

    Given a stream of integers and a window size, calculate the moving average of all integers in the sl ...

  3. LeetCode Moving Average from Data Stream

    原题链接在这里:https://leetcode.com/problems/moving-average-from-data-stream/ 题目: Given a stream of integer ...

  4. EMA计算的C#实现(c# Exponential Moving Average (EMA) indicator )

    原来国外有个源码(TechnicalAnalysisEngine src 1.25)内部对EMA的计算是: var copyInputValues = input.ToList(); for (int ...

  5. 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 ...

  6. 理解滑动平均(exponential moving average)

    1. 用滑动平均估计局部均值 滑动平均(exponential moving average),或者叫做指数加权平均(exponentially weighted moving average),可以 ...

  7. [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 ...

  8. tensorflow中moving average的用法

    一般在保存模型参数的时候,都会保存一份moving average,是取了不同迭代次数模型的移动平均,移动平均后的模型往往在性能上会比最后一次迭代保存的模型要好一些. tensorflow-model ...

  9. 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 ...

  10. [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 ...

随机推荐

  1. About Pull Strings 英语走后门议论文

    About pull strings Author : Pleiades_Antares 1. From ancient times to the present, the "going b ...

  2. 数据库訪问技术之JDBC

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/zhuojiajin/article/details/32150883     在了解JDBC之前呢, ...

  3. 《通过C#学Proto.Actor模型》之Persistence

    Actor是有状态的,当每一步执行失败后,返回失败地方继续执行时,希望此时的状态是正确的,为了保证这一点,持久化就成了必要的环节了. Proto.Actor提供了三种方式执久化: Event Sour ...

  4. 哈希长度扩展攻击(Hash Length Extension Attack)利用工具hexpand安装使用方法

    去年我写了一篇哈希长度扩展攻击的简介以及HashPump安装使用方法,本来已经足够了,但HashPump还不是很完善的哈希长度扩展攻击,HashPump在使用的时候必须提供original_data, ...

  5. 使用.net core efcore根据数据库结构自动生成实体类

    源码 github,已更新最新代码 https://github.com/leoparddne/GenEntities/ 使用的DB是mysql,所有先nuget一下mysql.data 创建t4模板 ...

  6. 深入Eureka/Feign/Hystrix原理学习(1)

    第一步: 创建注册中心项目,引入cloud discovery相关依赖. ①在pom文件中引入相关依赖. ②在启动类上加上@EnableEurekaServer注解,标注这是一个注 册中心. ③在ap ...

  7. 洛谷 P1088 火星人

    https://www.luogu.org/problemnew/show/P1088 这个题一开始是很蒙的 感觉很麻烦,每次都要交换balabala..... 后来才知道有这么一个神奇的stl 真是 ...

  8. Python——Django-form表单提交

    一.提交的注意事项 1. form不是from,所有获取用户输入的标签都应该放在form里面, input并且必须要有name属性 2. action属性控制往哪儿提交,method一般都设置成pos ...

  9. Linux下python3、virtualenv、Mysql、redis安装配置

    一.在Linux安装python解释器 1.下载python3源码包 cd /opt/ wget https://www.python.org/ftp/python/3.6.2/Python-3.6. ...

  10. 51Nod--1247 可能的路径(gcd)

    根据规则可知 假设 (a,b) 可以到达坐标(aa,bb) 那么 aa=a*x+b*y  x y 必定有解  所以 我们只要求两个坐标的gcd看是否相等就好 #include<bits/stdc ...