我分析与HTTP请求日志的AWS日志文件,我需要来预测下一分钟预期负载(请求数)。但是,我看到有一些没有任何记录的时间跨度。在这种情况下,我认为在那段时间负载只是0,或者我需要做某种内插的?
time load
-----------------------------------
2018-11-07 09:45:00 40
2018-11-07 09:46:00 45
2018-11-07 09:47:00 34
2018-11-07 09:48:00 56
然后在接下来的2小时,然后再没有日志:
time load
-----------------------------------
2018-11-07 11:50:00 54
2018-11-07 11:51:00 34
2018-11-07 11:52:00 23
2018-11-07 11:53:00 21
比方说,当我看到这个文件的熊猫数据帧为我的预测模型,我填写所有分钟的2小时0?还是有处理这类情况的更好的智能方法?
我建议用-1填充缺失值。一个ML模型应该学会面对这一切。当滑动平均值或其他插值方法填充值,则强制执行可能不恰当地表示数据的功能。该模型应该学会自己处理缺失值(并找到最好的方式meassured值之间进行插值)。
在这里,我有一个例子怎么可能是这样的:该模型考虑最后5个时间步长来预测未来的后续时间戳。
import numpy as np
from sklearn.ensemble import RandomForestRegressor
import matplotlib.pylab as plt
timeline = np.array([40, 45, 50, 53, 54, None, None, None, 50, 43, 30,
20, 15, 14, 13, 14, 16, 21, 27, 35, 46, 59, 65, 70,
None, None, 74, 72, 70, 65, 56, 44, 32, 26, 21, 18,
17, 16, 16, 17, 23, None, 47, 60, 75, None, 105,
111, 116, 118, 119, 118, 112, 103, None, None,
60, 53, 51, 52, 55, 62, None, 75, 77, 76, 74, 63,
50, 35])
plt.figure()
plt.plot(timeline)
plt.xlabel("time_index")
plt.ylabel("requests")
plt.show()
timeline[timeline==None] = -1
def get_training_data(timeline, n_time_steps=5):
x = []
y = []
for i in range(n_time_steps, len(timeline)):
x.append(timeline[i-n_time_steps:i])
y.append(timeline[i])
return np.array(x), np.array(y)
x, y = get_training_data(timeline)
from sklearn.ensemble import RandomForestRegressor
model = RandomForestRegressor()
# train model
model.fit(x, y)
pred = model.predict([y[-5:]])[0]
print 'the prediction for the future timestamp is:', pred
对于未来时间戳的预测是:30.8
现在,如果你有未知的值也适用:
model.predict(np.array([[10, 20, 30, -1, -1]]))
46.5
注意:
通常不是随机阿甘但回归神经网络(例如LSTMs)用于这样的时间序列的任务。但是,为了简单起见,我选择了一个简单的模型。
一种方法是,以填补缺失的日期与滚动平均值。否则,如果你在哪里,以配合其他值模型缺少的日期,说0
,模型可能会也把这些值考虑在内,以预测,(因为没有预测就其历史将有遗漏值),这肯定会恶化的预测结果。
所以说你有:
time load
0 2018-11-07 09:45:00 40
1 2018-11-07 09:46:00 45
2 2018-11-07 09:47:00 34
3 2018-11-07 09:49:00 56
您可以通过使用.resample
重采样数据框开始,并使用.rolling
,这将与给定的窗口长度的滚动平均值填补填补缺失值:
df.time = pd.to_datetime(df.time)
resampled = df.set_index('time').resample('Min').first()
fill = resampled.rolling(3,center=True,min_periods=1).mean()
resampled.fillna(fill)
load
time
2018-11-07 09:45:00 40.0
2018-11-07 09:46:00 45.0
2018-11-07 09:47:00 34.0
2018-11-07 09:48:00 45.0
2018-11-07 09:49:00 56.0
使用tsclean(),它会自动处理缺失值和异常值。