基于Holt-Winters方法对资源进行预测
生活随笔
收集整理的這篇文章主要介紹了
基于Holt-Winters方法对资源进行预测
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
??Holt-Winters方法是一種時(shí)間序列分析和預(yù)報(bào)方法。該方法對含有線性趨勢和周期波動的非平穩(wěn)序列適用,利用指數(shù)平滑法(EMA)讓模型參數(shù)不斷適應(yīng)非平穩(wěn)序列的變化,并對未來趨勢進(jìn)行短期預(yù)報(bào)。現(xiàn)實(shí)場景中如國家GDP歷年數(shù)據(jù),機(jī)器cpu利用率,內(nèi)存數(shù)據(jù)等都是時(shí)間序列。對未來時(shí)間的觀測值進(jìn)行預(yù)測是有意義的工作,提前預(yù)知未來的數(shù)據(jù)的走勢,可以提前做出行動,如預(yù)測cpu使用率,如果cpu飆高,可以及早進(jìn)行調(diào)整,避免機(jī)器負(fù)載過高而宕機(jī),這個(gè)在AIOPS是很常見的一個(gè)應(yīng)用場景。
代碼示例 # import needed packages #-----------------------import math import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import linear_model from scipy.optimize import fmin_l_bfgs_bsdata = open('data.csv') tsA = sdata.read().split('\n') tsA.remove("") tsA = list(map(int, tsA)) source_len = len(tsA)def holtWinters(ts, p, sp, ahead, mtype, alpha = None, beta = None, gamma = None):a, b, s = _initValues(mtype, ts, p, sp)if alpha == None or beta == None or gamma == None:ituning = [0.1, 0.1, 0.1]ibounds = [(0,1), (0,1), (0,1)]optimized = fmin_l_bfgs_b(_MSD, ituning, args = (mtype, ts, p, a, b, s[:]), bounds = ibounds, approx_grad = True)alpha, beta, gamma = optimized[0]MSD, params, smoothed = _expSmooth(mtype, ts, p, a, b, s[:], alpha, beta, gamma)predicted = _predictValues(mtype, p, ahead, params)return {'alpha': alpha, 'beta': beta, 'gamma': gamma, 'MSD': MSD, 'params': params, 'smoothed': smoothed, 'predicted': predicted}def _initValues(mtype, ts, p, sp):initSeries = pd.Series(ts[:p*sp])if mtype == 'additive':rawSeason = initSeries - initSeries.rolling(window=p, min_periods=p, center=True).mean()initSeason = [np.nanmean(rawSeason[i::p]) for i in range(p)]initSeason = pd.Series(initSeason) - np.mean(initSeason)deSeasoned = [initSeries[v] - initSeason[v % p] for v in range(len(initSeries))]else:rawSeason = initSeries / initSeries.rolling(window = p, min_periods = p, center = True).mean()initSeason = [np.nanmean(rawSeason[i::p]) for i in range(p)]initSeason = pd.Series(initSeason) / math.pow(np.prod(np.array(initSeason)), 1/p)deSeasoned = [initSeries[v] / initSeason[v % p] for v in range(len(initSeries))]lm = linear_model.LinearRegression()lm.fit(pd.DataFrame({'time': [t+1 for t in range(len(initSeries))]}), pd.Series(deSeasoned))return float(lm.intercept_), float(lm.coef_), list(initSeason)def _MSD(tuning, *args):predicted = []mtype = args[0]ts, p = args[1:3]Lt1, Tt1 = args[3:5]St1 = args[5][:]alpha, beta, gamma = tuning[:]for t in range(len(ts)):if mtype == 'additive':Lt = alpha * (ts[t] - St1[t % p]) + (1 - alpha) * (Lt1 + Tt1)Tt = beta * (Lt - Lt1) + (1 - beta) * (Tt1)St = gamma * (ts[t] - Lt) + (1 - gamma) * (St1[t % p])predicted.append(Lt1 + Tt1 + St1[t % p])else:Lt = alpha * (ts[t] / St1[t % p]) + (1 - alpha) * (Lt1 + Tt1)Tt = beta * (Lt - Lt1) + (1 - beta) * (Tt1)St = gamma * (ts[t] / Lt) + (1 - gamma) * (St1[t % p])predicted.append((Lt1 + Tt1) * St1[t % p])Lt1, Tt1, St1[t % p] = Lt, Tt, Streturn sum([(ts[t] - predicted[t])**2 for t in range(len(predicted))])/len(predicted)def _expSmooth(mtype, ts, p, a, b, s, alpha, beta, gamma):smoothed = []Lt1, Tt1, St1 = a, b, s[:]for t in range(len(ts)):if mtype == 'additive':Lt = alpha * (ts[t] - St1[t % p]) + (1 - alpha) * (Lt1 + Tt1)Tt = beta * (Lt - Lt1) + (1 - beta) * (Tt1)St = gamma * (ts[t] - Lt) + (1 - gamma) * (St1[t % p])smoothed.append(Lt1 + Tt1 + St1[t % p])else:Lt = alpha * (ts[t] / St1[t % p]) + (1 - alpha) * (Lt1 + Tt1)Tt = beta * (Lt - Lt1) + (1 - beta) * (Tt1)St = gamma * (ts[t] / Lt) + (1 - gamma) * (St1[t % p])smoothed.append((Lt1 + Tt1) * St1[t % p])Lt1, Tt1, St1[t % p] = Lt, Tt, StMSD = sum([(ts[t] - smoothed[t])**2 for t in range(len(smoothed))])/len(smoothed)return MSD, (Lt1, Tt1, St1), smootheddef _predictValues(mtype, p, ahead, params):'''subroutine to generate predicted values @ahead periods into the future'''Lt, Tt, St = paramsif mtype == 'additive':return [Lt + (t+1)*Tt + St[t % p] for t in range(ahead)]else:return [(Lt + (t+1)*Tt) * St[t % p] for t in range(ahead)]results = holtWinters(tsA, 12, 4, 24, mtype = 'additive') results = holtWinters(tsA, 12, 4, 24, mtype = 'multiplicative')print("TUNING: ", results['alpha'], results['beta'], results['gamma'], results['MSD']) print("FINAL PARAMETERS: ", results['params']) print("PREDICTED VALUES: ", results['predicted']) last_len =len(results['predicted']) x1 = range(0, source_len) x2 = range(source_len, source_len + last_len) y1 = tsA y2 = results['predicted'] fig = plt.figure() plt.plot(x1, y1, marker=r'', color=u'blue', linestyle='-', label='Initial value') plt.plot(x2, y2, marker=r'', color=u'red', linestyle='-', label='Estimate value') plt.xlabel('time') plt.ylabel('value') plt.legend(loc='best') plt.savefig('line_plot.png', dpi=400, bbox_inches='tight') plt.show()
總結(jié)
以上是生活随笔為你收集整理的基于Holt-Winters方法对资源进行预测的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 赋予图片以png结尾的网址
- 下一篇: 将数据写入数据库:打开数据库,建库建表,