移动平均算法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. Redis操作list

    来自:http://www.cnblogs.com/alex3714/articles/6217453.html List操作,redis中的List在在内存中按照一个name对应一个List来存储. ...

  2. 【Python使用】使用pip安装卸载Python包(含离线安装Python包)未完成???

    pip 是 Python 包管理工具,该工具提供了对Python包的查找.下载.安装.卸载的功能.Python 2.7.9 + 或 Python 3.4+ 以上版本都自带 pip 工具. pip使用( ...

  3. vue 用less

    https://blog.csdn.net/u013746071/article/details/79655042

  4. Centos安装php php-fpm 以及 配置nginx

    下载php源码包 http://www.php.net/downloads.php 安装php .tar.bz2 cd php- ./configure --prefix=/usr/local/php ...

  5. Strem_01

    import 'package:flutter/material.dart';import 'dart:async';import 'dart:ui'; void main()=>runApp( ...

  6. 分布式任务调度平台XXL-JOB搭建教程

    关于分布式任务调度平台XXL-JOB,其实作者 许雪里 在其发布的中文教程中已经介绍的很清楚了,这里我就不做过多的介绍了,关于其搭建教程,本人依照其文档搭建起来基本上也没遇到啥问题,这里通过博客的形式 ...

  7. C#中的虚函数及继承关系

    转载:http://blog.csdn.net/suncherrydream/article/details/8423991 若一个实例方法声明前带有virtual关键字,那么这个方法就是虚方法. 虚 ...

  8. 一些很容易被忘记的css

    一些很偏门的css,用过一两次,很难记得牢,这里,我总结一些. outline 当input选中的时候会出现一个边框 /*一般设置成 none*/ textarea:focus, input:focu ...

  9. HDU 3518 Boring counting

    题目:Boring counting 链接:http://acm.hdu.edu.cn/showproblem.php?pid=3518 题意:给一个字符串,问有多少子串出现过两次以上,重叠不能算两次 ...

  10. mysql int(19) float(7,2) decimal(7,2)对比

    nt(19):指定数字的显示宽度为19,与实际存储数值的范围无关 float(7,2):  7是显示宽度指示器,指定显示的浮点数为7位数字(与float实际存储值的范围无关),2代表小数点后只有两位小 ...