## MovingAverage-滑动平均

| |
[ 所属分类 开发（python） | 发布者 店小二04 | 时间 2017 | 作者 红领巾 ] 0人收藏点击收藏

MovingAverage 可翻译为滑动平均或移动平均，是做时间序列预测时用到的简单方法。

class MovingAverage { public: explicit MovingAverage(int window); ~MovingAverage(); void Clear(); double GetAverage() const; void AddValue(double v); private: const int window_;// Max size of interval double sum_;// Sum over interval double* data_;// Actual data values int head_;// Offset of the newest statistic in data_ int count_;// # of valid data elements in window }; // 构造函数 MovingAverage::MovingAverage(int window) : window_(window), sum_(0.0), data_(new double[window_]), head_(0), count_(0) { CHECK_GE(window, 1); } // 析构函数 MovingAverage::~MovingAverage() { delete[] data_; } void MovingAverage::Clear() { count_ = 0; head_ = 0; sum_ = 0; } double MovingAverage::GetAverage() const { if (count_ == 0) { return 0; } else { return static_cast<double>(sum_) / count_; } } void MovingAverage::AddValue(double v) { if (count_ < window_) { // This is the warmup phase. We don't have a full window's worth of data. head_ = count_; data_[count_++] = v; } else { if (window_ == ++head_) { head_ = 0; } // Toss the oldest element sum_ -= data_[head_]; // Add the newest element data_[head_] = v; } sum_ += v; }

import matplotlib.pyplotas plt import pandasas pd import requests import io import numpyas np def moving_average(l, N): sum = 0 result = list( 0 for x in l) for i in range( 0, N ): sum = sum + l[i] result[i] = sum / (i+1) for i in range( N, len(l) ): sum = sum - l[i-N] + l[i] result[i] = sum / N return result # 使用效率更高的numpy # http://stackoverflow.com/questions/13728392/moving-average-or-running-mean def fast_moving_average(x, N): return np.convolve(x, np.ones((N,))/N)[(N-1):] url = 'http://blog.topspeedsnail.com/wp-content/uploads/2016/12/铁路客运量.csv' ass_data = requests.get(url).content df = pd.read_csv(io.StringIO(ass_data.decode('utf-8')))# python2使用StringIO.StringIO data = np.array(df['铁路客运量_当期值(万人)']) ma_data = moving_average(data.to_list(), 3) plt.figure() plt.plot(data, color='g') plt.plot(ma_data, color='r') plt.show()