移动平均算法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. 解决IntelliJ IDEA 创建Maven项目速度慢问题

    IntelliJ IDEA 创建maven项目速度很慢,甚至卡住不动了. 原因 IDEA根据maven archetype的本质,其实是执行mvn archetype:generate命令,该命令执行 ...

  2. Hadoop的NullWritable

    NullWritable是Writable的一个特殊类,实现方法为空实现,不从数据流中读数据,也不写入数据,只充当占位符,如在MapReduce中,如果你不需要使用键或值,你就可以将键或值声明为Nul ...

  3. CF452F Permutations/Luogu2757 等差子序列 树状数组、Hash

    传送门--Luogu 传送门--Codeforces 如果存在长度\(>3\)的等差子序列,那么一定存在长度\(=3\)的等差子序列,所以我们只需要找长度为\(3\)的等差子序列.可以枚举等差子 ...

  4. 【转帖】系统软件工程师必备技能-进程内存的working set size(WSS)测量

    系统软件工程师必备技能-进程内存的working set size(WSS)测量 2018年12月28日 18:43:01 Linuxer_ 阅读数:145 https://blog.csdn.net ...

  5. vue mock自己总结

    cli安装mock模块 npm   install  mockjs 创建mock文件夹 配置及创建文件 当后端写好真实接口以后,我们只需删掉创建的mock.js文件和在main.js中导入假数据的那行 ...

  6. Android——图片轮播

    Android技术——轮播功能 轮播需要什么? 答:实现图片与广告语展示.循环播发以及手动切换.支持加载本地与网络图片. 性能优化? 答:多张图片与指示器展示.自动与定时.循环播发.滑动流畅并且无卡顿 ...

  7. golang函数

    一.函数语法 func 函数名(形参列表) (返回值列表){ ...... return 返回值 } 例如: package main import "fmt" func test ...

  8. OTZ%%%子谦。大佬

    又上了节课...俩题 计算系数    组合数问题... 要不是大佬指点就只能阶乘暴力算了 (主要还是我忘了杨辉三角) 杨辉三角与组合数C有着千丝万缕的联系,在计算,使用方面相当方便. 先说计算系数 计 ...

  9. UVA 10618 Tango Tango Insurrection

    https://vjudge.net/problem/UVA-10618 题目 你想学着玩跳舞机.跳舞机的踏板上有4个箭头:上.下.左.右.当舞曲开始时,屏幕上会有一些箭头往上移动.当向上移动箭头与顶 ...

  10. 基于scrapy-redis的分布式爬虫

    一.介绍 1.原生的scrapy框架 原生的scrapy框架是实现不了分布式的,其原因有: 1. 因为多台机器上部署的scrapy会各自拥有各自的调度器,这样就使得多台机器无法分配start_urls ...