移动平均算法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. java类加载及类初始化

    1.前言 java是跨平台语言,主要是因为它的java虚拟机的存在,java有事编译语言,所以需要将编写的java文件编译成jvm可运用的class字节码文件.在java中一切皆对象.对于Java虚拟 ...

  2. .NET MVC全局异常处理(一)

    目录 .NET MVC全局异常处理 IIS配置 静态错误页配置 .NET错误页配置 程序设置 全局异常配置 .NET MVC全局异常处理 一直知道有.NET有相关的配置,但没有实际做过,以为改下设定就 ...

  3. 【Python 05】Python开发环境搭建

    Python3安装和使用 1.安装 Python管方下载地址 选择Customize installation安装,并且勾选Add Python 3.X to PATH. 勾选Documentatio ...

  4. web框架开发-Django用户认证组件

    可以用认证组件做什么 针对session的缺陷, 跟新数据时,不跟新key键, 用户认证组件是删除后再重建 用户认证组件很多功能可以直接使用 利用用户认证表(auth_user,通过Django自己创 ...

  5. Vuex初级入门及简单案例

    1.为什么要使用Vuex? (1)方便所有组件共享信息,方便不同组件共享信息. (2)某个组件需要修改状态和需求.   2.状态有哪些? (1)组件内部定义的data状态(通过组件内部修改) (2)组 ...

  6. (十二)Deleting Documents

    Deleting a document is fairly straightforward. This example shows how to delete our previous custome ...

  7. .net core下用HttpClient和asp.net core实现https的双向认证

    关于https双向认证的知识可先行google,这时矸接代码. 为了双向认证,我们首先得准备两个crt证书,一个是client.crt,一个是server.crt,有时为了验证是否同一个根证书的验证, ...

  8. 6-STM32物联网开发WIFI(ESP8266)+GPRS(Air202)系统方案升级篇-优化升级(安装Apache (Web服务器)软件,测试HTTP)

    为了和SDK升级保持协议一致,花了两天时间实现了用LUA开发,MQTT+HTTP方式实现远程升级 安装Apache主要是为了实现通过HTTP下载资源 升级介绍: 0,用户点击检查更新时,APP首先通过 ...

  9. BZOJ1000-1099板刷计划+一句话题解 73/100

    1000-1009 1000A+B Problem 这个还要写??? 1001 狼抓兔子 平面图最小割转化为对偶图最短路 #include<bits/stdc++.h> #define i ...

  10. Gerrit 添加用户

    使用ssh添加用户 ssh name@localhost -p 29418 gerrit create-account username --email username@email --full-n ...