data download:

https://github.com/nicolasmiller/pyculiarity/blob/master/tests/raw_data.csv

数据集样子:

                           y
timestamp
1980-09-25 14:01:00  182.478
1980-09-25 14:02:00  176.231
1980-09-25 14:03:00  183.917
1980-09-25 14:04:00  177.798
1980-09-25 14:05:00  165.469
1980-09-25 14:06:00  181.878
1980-09-25 14:07:00  184.502
1980-09-25 14:08:00  183.303
1980-09-25 14:09:00  177.578
1980-09-25 14:10:00  171.641
1980-09-25 14:11:00  191.014
1980-09-25 14:12:00  184.068
1980-09-25 14:13:00  188.457
1980-09-25 14:14:00  175.739
1980-09-25 14:15:00  175.524
1980-09-25 14:16:00  189.128
1980-09-25 14:17:00  176.885
1980-09-25 14:18:00  167.140
1980-09-25 14:19:00  173.723
1980-09-25 14:20:00  168.460
1980-09-25 14:21:00  177.623
1980-09-25 14:22:00  183.888

做了shift处理前后:

                           y
timestamp
1980-09-25 14:01:00  182.478
1980-09-25 14:02:00  176.231
1980-09-25 14:03:00  183.917
1980-09-25 14:04:00  177.798
1980-09-25 14:05:00  165.469
1980-09-25 14:06:00  181.878
1980-09-25 14:07:00  184.502
1980-09-25 14:08:00  183.303
1980-09-25 14:09:00  177.578
1980-09-25 14:10:00  171.641
1980-09-25 14:11:00  191.014
1980-09-25 14:12:00  184.068
1980-09-25 14:13:00  188.457
1980-09-25 14:14:00  175.739
1980-09-25 14:15:00  175.524
1980-09-25 14:16:00  189.128
1980-09-25 14:17:00  176.885
1980-09-25 14:18:00  167.140
1980-09-25 14:19:00  173.723
1980-09-25 14:20:00  168.460
1980-09-25 14:21:00  177.623
1980-09-25 14:22:00  183.888
1980-09-25 14:23:00  167.487
1980-09-25 14:24:00  165.572
1980-09-25 14:25:00  170.480
1980-09-25 14:26:00  172.474
1980-09-25 14:27:00  166.448
1980-09-25 14:28:00  163.098
1980-09-25 14:29:00  163.544
1980-09-25 14:30:00  163.816y    lag_6   ...      lag_23   lag_24
timestamp                               ...
1980-09-25 14:01:00  182.478      NaN   ...         NaN      NaN
1980-09-25 14:02:00  176.231      NaN   ...         NaN      NaN
1980-09-25 14:03:00  183.917      NaN   ...         NaN      NaN
1980-09-25 14:04:00  177.798      NaN   ...         NaN      NaN
1980-09-25 14:05:00  165.469      NaN   ...         NaN      NaN
1980-09-25 14:06:00  181.878      NaN   ...         NaN      NaN
1980-09-25 14:07:00  184.502  182.478   ...         NaN      NaN
1980-09-25 14:08:00  183.303  176.231   ...         NaN      NaN
1980-09-25 14:09:00  177.578  183.917   ...         NaN      NaN
1980-09-25 14:10:00  171.641  177.798   ...         NaN      NaN
1980-09-25 14:11:00  191.014  165.469   ...         NaN      NaN
1980-09-25 14:12:00  184.068  181.878   ...         NaN      NaN
1980-09-25 14:13:00  188.457  184.502   ...         NaN      NaN
1980-09-25 14:14:00  175.739  183.303   ...         NaN      NaN
1980-09-25 14:15:00  175.524  177.578   ...         NaN      NaN
1980-09-25 14:16:00  189.128  171.641   ...         NaN      NaN
1980-09-25 14:17:00  176.885  191.014   ...         NaN      NaN
1980-09-25 14:18:00  167.140  184.068   ...         NaN      NaN
1980-09-25 14:19:00  173.723  188.457   ...         NaN      NaN
1980-09-25 14:20:00  168.460  175.739   ...         NaN      NaN
1980-09-25 14:21:00  177.623  175.524   ...         NaN      NaN
1980-09-25 14:22:00  183.888  189.128   ...         NaN      NaN
1980-09-25 14:23:00  167.487  176.885   ...         NaN      NaN
1980-09-25 14:24:00  165.572  167.140   ...     182.478      NaN
1980-09-25 14:25:00  170.480  173.723   ...     176.231  182.478
1980-09-25 14:26:00  172.474  168.460   ...     183.917  176.231
1980-09-25 14:27:00  166.448  177.623   ...     177.798  183.917
1980-09-25 14:28:00  163.098  183.888   ...     165.469  177.798
1980-09-25 14:29:00  163.544  167.487   ...     181.878  165.469
1980-09-25 14:30:00  163.816  165.572   ...     184.502  181.878

代码:

# coding: utf-8import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.model_selection import TimeSeriesSplit  # you have everything done for you
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LassoCV, RidgeCV# for time-series cross-validation set 5 folds
tscv = TimeSeriesSplit(n_splits=5)def mean_absolute_percentage_error(y_true, y_pred):return np.mean(np.abs((y_true - y_pred) / y_true)) * 100def timeseries_train_test_split(X, y, test_size):"""Perform train-test split with respect to time series structure"""# get the index after which test set startstest_index = int(len(X) * (1 - test_size))X_train = X.iloc[:test_index]y_train = y.iloc[:test_index]X_test = X.iloc[test_index:]y_test = y.iloc[test_index:]return X_train, X_test, y_train, y_testdef plotModelResults(model, X_train, X_test, y_train, y_test, plot_intervals=False, plot_anomalies=False):"""Plots modelled vs fact values, prediction intervals and anomalies"""prediction = model.predict(X_test)plt.figure(figsize=(15, 7))plt.plot(prediction, "g", label="prediction", linewidth=2.0)plt.plot(y_test.values, label="actual", linewidth=2.0)if plot_intervals:cv = cross_val_score(model, X_train, y_train,cv=tscv,scoring="neg_mean_absolute_error")mae = cv.mean() * (-1)deviation = cv.std()scale = 20lower = prediction - (mae + scale * deviation)upper = prediction + (mae + scale * deviation)plt.plot(lower, "r--", label="upper bond / lower bond", alpha=0.5)plt.plot(upper, "r--", alpha=0.5)if plot_anomalies:anomalies = np.array([np.NaN] * len(y_test))anomalies[y_test < lower] = y_test[y_test < lower]anomalies[y_test > upper] = y_test[y_test > upper]plt.plot(anomalies, "o", markersize=10, label="Anomalies")error = mean_absolute_percentage_error(prediction, y_test)plt.title("Mean absolute percentage error {0:.2f}%".format(error))plt.legend(loc="best")plt.tight_layout()plt.grid(True);plt.savefig("linear.png")def plotCoefficients(model, X_train):"""Plots sorted coefficient values of the model"""coefs = pd.DataFrame(model.coef_, X_train.columns)coefs.columns = ["coef"]coefs["abs"] = coefs.coef.apply(np.abs)coefs = coefs.sort_values(by="abs", ascending=False).drop(["abs"], axis=1)plt.figure(figsize=(20, 12))coefs.coef.plot(kind='bar')plt.grid(True, axis='y')plt.hlines(y=0, xmin=0, xmax=len(coefs), linestyles='dashed')plt.savefig("linear-cov.png")def code_mean(data, cat_feature, real_feature):"""Returns a dictionary where keys are unique categories of the cat_feature,and values are means over real_feature"""return dict(data.groupby(cat_feature)[real_feature].mean())def prepareData(series, lag_start, lag_end, test_size, target_encoding=False):"""series: pd.DataFramedataframe with timeserieslag_start: intinitial step back in time to slice target variableexample - lag_start = 1 means that the modelwill see yesterday's values to predict todaylag_end: intfinal step back in time to slice target variableexample - lag_end = 4 means that the modelwill see up to 4 days back in time to predict todaytest_size: floatsize of the test dataset after train/test split as percentage of datasettarget_encoding: booleanif True - add target averages to the dataset"""# copy of the initial datasetdata = pd.DataFrame(series.copy())data.columns = ["y"]# lags of seriesfor i in range(lag_start, lag_end):data["lag_{}".format(i)] = data.y.shift(i)# datetime features# data.index = data.index.to_datetime()data["hour"] = data.index.hourdata["weekday"] = data.index.weekdaydata['is_weekend'] = data.weekday.isin([5, 6]) * 1if target_encoding:# calculate averages on train set onlytest_index = int(len(data.dropna()) * (1 - test_size))data['weekday_average'] = list(map(code_mean(data[:test_index], 'weekday', "y").get, data.weekday))data["hour_average"] = list(map(code_mean(data[:test_index], 'hour', "y").get, data.hour))# drop encoded variables# data.drop(["hour", "weekday"], axis=1, inplace=True)# train-test splity = data.dropna().yX = data.dropna().drop(['y'], axis=1)X_train, X_test, y_train, y_test = \timeseries_train_test_split(X, y, test_size=test_size)return X_train, X_test, y_train, y_testdef plt_linear():data = pd.read_csv('raw_data.csv', usecols=['timestamp', 'count'])data['timestamp'] = pd.to_datetime(data['timestamp'])data.set_index("timestamp", drop=True, inplace=True)data.rename(columns={'count': 'y'}, inplace=True)X_train, X_test, y_train, y_test = \prepareData(data, lag_start=6, lag_end=25, test_size=0.3, target_encoding=True)scaler = StandardScaler()X_train_scaled = scaler.fit_transform(X_train)X_test_scaled = scaler.transform(X_test)# lr = LinearRegression()lr = LassoCV(cv=tscv)# lr = RidgeCV(cv=tscv)# lr.fit(X_train_scaled, y_train)"""from xgboost import XGBRegressorlr = XGBRegressor()# lr = xgb.XGBRegressor(max_depth=5, learning_rate=0.1, n_estimators=160, silent=False, objective='reg:gamma')"""lr.fit(X_train_scaled, y_train)"""IMPORTANTGenerally tree-based models poorly handle trends in data, compared to linear models, so you have to detrend your series first or use some tricks to make the magic happen. Ideally make the series stationary and then use XGBoost, for example, you can forecast trend separately with a linear model and then add predictions from xgboost to get final forecast."""plotModelResults(lr, X_train=X_train_scaled, X_test=X_test_scaled,  y_train=y_train, y_test=y_test, plot_intervals=True, plot_anomalies=True)plotCoefficients(lr, X_train=X_train)plt_linear()

可以看到相关系数!

重构代码,使其可以预测未来:

# coding: utf-8import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.model_selection import TimeSeriesSplit
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LassoCV, RidgeCVdef mean_absolute_percentage_error(y_true, y_pred):return np.mean(np.abs((y_true - y_pred) / y_true)) * 100def timeseries_train_test_split(X, y, test_size, predict_size):"""Perform train-test split with respect to time series structure"""total_size = len(X)# get the index after which test set startstest_index = int(total_size * (1 - test_size))X_train = X.iloc[:test_index]y_train = y.iloc[:test_index]X_test = X.iloc[test_index:total_size-predict_size]y_test = y.iloc[test_index:total_size-predict_size]X_predict = X.iloc[-predict_size:]y_predict = y.iloc[-predict_size:]return X_train, X_test, y_train, y_test, X_predict, y_predictdef predict_future(lr, X_predict, y_predict, lag_start, lag_end, scaler):# for predict# not OK for abnormal real valuey_predict[0:lag_start] = lr.predict(scaler.transform(X_predict.iloc[0:lag_start]))# last_line = X_test.iloc[-1]for i in range(lag_start, len(X_predict)):# for i in range(0, len(X_predict)):last_line = X_predict.iloc[i-1]index = X_predict.index[i]for j in range(lag_end-1, lag_start):X_predict.at[index, "lag_{}".format(j)] = last_line["lag_{}".format(j-1)]X_predict.at[index, "lag_{}".format(lag_start)] = y_predict[i-1]y_predict[i] = lr.predict(scaler.transform([X_predict.iloc[i]]))[0]return y_predictdef plot_results(y_predict, y, intervals, img_filename, plot_intervals=False, plot_anomalies=False, extra_plot=None):"""Plots modelled vs fact values, prediction intervals and anomalies"""assert len(y_predict) == len(y)plt.figure(figsize=(15, 7))# plt.plot(y.index, y_predict, "g", label="prediction", linewidth=3.0)# plt.plot(y.index, y.values, label="actual", linewidth=1.0)plt.plot(y.index, y_predict, ls='-', c='#0072B2', label='predicted y')plt.plot(y.index, y.values, 'k.', label='y')if extra_plot is not None:# plt.plot(extra_plot.index, extra_plot.values, "y", label="future predict", linewidth=3.0)plt.plot(extra_plot.index, extra_plot.values, 'y', label='predicted y')if plot_intervals:lower = y_predict - intervalsupper = y_predict + intervals# plt.plot(y.index, lower, "r--", label="upper bond / lower bond", alpha=0.5)# plt.plot(y.index, upper, "r--", alpha=0.5)plt.fill_between(y.index, lower, upper, color='#0072B2', alpha=0.2, label='predicted upper/lower y')if extra_plot is not None:# plt.plot(extra_plot.index, extra_plot.values-intervals, "r--", label="upper bond / lower bond", alpha=0.5)# plt.plot(extra_plot.index, extra_plot.values+intervals, "r--", alpha=0.5)plt.fill_between(extra_plot.index, extra_plot.values-intervals, extra_plot.values+intervals,color='#0072B2', alpha=0.2, label='predicted upper/lower y')if plot_anomalies:anomalies_lower = y[y < lower]anomalies_upper = y[y > upper]# plt.plot(anomalies_lower.index, anomalies_lower.values, "ro", markersize=10, label="Anomalies(+)")# plt.plot(anomalies_upper.index, anomalies_upper.values, "ro", markersize=10, label="Anomalies(-)")plt.plot(anomalies_lower.index, anomalies_lower.values, "rX", label='abnormal points')plt.plot(anomalies_upper.index, anomalies_upper.values, "rX")error = mean_absolute_percentage_error(y_predict, y)plt.title("Mean absolute percentage error {0:.2f}%".format(error))plt.legend(loc="best")plt.tight_layout()plt.grid(True);plt.savefig(img_filename)def plot_arg_importance(model, X_train):"""Plots sorted coefficient values of the model"""coefs = pd.DataFrame(model.coef_, X_train.columns)coefs.columns = ["coef"]coefs["abs"] = coefs.coef.apply(np.abs)coefs = coefs.sort_values(by="abs", ascending=False).drop(["abs"], axis=1)plt.figure(figsize=(20, 12))coefs.coef.plot(kind='bar')plt.grid(True, axis='y')plt.hlines(y=0, xmin=0, xmax=len(coefs), linestyles='dashed')plt.savefig("linear-cov.png")def code_mean(data, cat_feature, real_feature):"""Returns a dictionary where keys are unique categories of the cat_feature,and values are means over real_feature"""return dict(data.groupby(cat_feature)[real_feature].mean())def prepare_data(series, lag_start, lag_end, test_size, target_encoding=False, days_to_predict=1):"""series: pd.DataFramedataframe with timeserieslag_start: intinitial step back in time to slice target variableexample - lag_start = 1 means that the modelwill see yesterday's values to predict todaylag_end: intfinal step back in time to slice target variableexample - lag_end = 4 means that the modelwill see up to 4 days back in time to predict todaytest_size: floatsize of the test dataset after train/test split as percentage of datasettarget_encoding: booleanif True - add target averages to the dataset"""last_date = series["timestamp"].max()def make_future_date(periods, freq='D'):"""Simulate the trend using the extrapolated generative model.Parameters----------periods: Int number of periods to forecast forward.freq: Any valid frequency for pd.date_range, such as 'D' or 'M'.Returns-------pd.Dataframe that extends forward from the end of self.history for therequested number of periods."""dates = pd.date_range(start=last_date,periods=periods + 1,  # An extra in case we include startfreq=freq)dates = dates[dates > last_date]  # Drop start if equals last_datereturn dates[:periods]  # Return correct number of periodspredict_points = days_to_predict * 1440 # 1 day = 60*24 minutesfuture_dates = make_future_date(periods=predict_points, freq='T')df_future = pd.DataFrame({"timestamp": future_dates, "y": np.zeros(len(future_dates))})data = pd.concat([series, df_future])data.set_index("timestamp", drop=True, inplace=True)# data = pd.DataFrame(series.copy())# data.columns = ["y"]print(data[:30])# lags of seriesfor i in range(lag_start, lag_end):data["lag_{}".format(i)] = data.y.shift(i)print(data[:30])# datetime features# data.index = data.index.to_datetime()data["hour"] = data.index.hourdata["weekday"] = data.index.weekdaydata['is_weekend'] = data.weekday.isin([5, 6]) * 1if target_encoding:# calculate averages on train set onlytest_index = int(len(data.dropna()) * (1 - test_size))data['weekday_average'] = list(map(code_mean(data[:test_index], 'weekday', "y").get, data.weekday))data["hour_average"] = list(map(code_mean(data[:test_index], 'hour', "y").get, data.hour))# drop encoded variables# data.drop(["hour", "weekday"], axis=1, inplace=True)# train-test splity = data.dropna().yX = data.dropna().drop(['y'], axis=1)X_train, X_test, y_train, y_test, X_predict, y_predict = \timeseries_train_test_split(X, y, test_size=test_size, predict_size=predict_points)return X_train, X_test, y_train, y_test, X_predict, y_predictdef calculate_intevals(lr, X_train, y_train, tscv):cv = cross_val_score(lr, X_train, y_train,cv=tscv,scoring="neg_mean_absolute_error")mae = cv.mean() * (-1)deviation = cv.std()scale = 30return  mae + scale * deviationdef plt_linear():data = pd.read_csv('raw_data.csv', usecols=['timestamp', 'count'])# input formatdata['timestamp'] = pd.to_datetime(data['timestamp'])data = data.sort_values('timestamp')data.rename(columns={'count': 'y'}, inplace=True)lag_start = 1lag_end = 100X_train, X_test, y_train, y_test, X_predict, y_predict = \prepare_data(data, lag_start=lag_start, lag_end=lag_end, test_size=0.3, target_encoding=True)scaler = StandardScaler()X_train_scaled = scaler.fit_transform(X_train)X_test_scaled = scaler.transform(X_test)# for time-series cross-validation set 5 foldstscv = TimeSeriesSplit(n_splits=5)# lr = LinearRegression()lr = LassoCV(cv=tscv)# lr = RidgeCV(cv=tscv)lr.fit(X_train_scaled, y_train)intervals = calculate_intevals(lr, X_train, y_train, tscv)"""y_test_predict = lr.predict(X_test_scaled)plot_results(y_predict=y_test_predict, y=y_test, intervals=intervals, img_filename="linear-test-result.png", plot_intervals=True, plot_anomalies=True)"""y2 = lr.predict(np.concatenate((X_train_scaled, X_test_scaled)))y = pd.concat([y_train, y_test])# plot_results(y_predict=y2, y=y, intervals=intervals, img_filename="linear-all-result.png", plot_intervals=True, plot_anomalies=True)y_future = predict_future(lr, X_predict, y_predict, lag_start, lag_end, scaler)plot_results(y_predict=y2, y=y, intervals=intervals, img_filename="linear-all.png", plot_intervals=True, plot_anomalies=True, extra_plot=y_future)plot_arg_importance(lr, X_train=X_train)plt_linear()

绘图:

尤其关键的是,lag_start, lag_end参数,如果lag_start=1,则表示使用前一个时刻输入,会导致模型过拟合,因此上面设置了lag_start=60表示使用一个小时前的数据来预测,防止过拟合。

来lag_start=1的效果:

可以看到,前一个时刻数据值的重要性!因此,最后做趋势预测的时候出现了重大失误,模型过拟合了。

bug修复:

# coding: utf-8import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.model_selection import TimeSeriesSplit
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LassoCV, RidgeCV
from sklearn.ensemble import GradientBoostingRegressordef mean_absolute_percentage_error(y_true, y_pred):return np.mean(np.abs((y_true - y_pred) / y_true)) * 100def predict_future(lr, X_predict, y_predict, lag_start, lag_end, scaler):# for predicty_predict[0:lag_start] = lr.predict(scaler.transform(X_predict.iloc[0:lag_start]))for i in range(lag_start, len(X_predict)):last_line = X_predict.iloc[i-1]index = X_predict.index[i]for j in range(lag_end-1, lag_start, -1):X_predict.at[index, "lag_{}".format(j)] = last_line["lag_{}".format(j-1)]X_predict.at[index, "lag_{}".format(lag_start)] = y_predict[i-1]y_predict[i] = lr.predict(scaler.transform([X_predict.iloc[i]]))[0]return y_predictdef plot_results(y_predict, y, intervals, img_filename, plot_intervals=False, plot_anomalies=False, extra_plot=None):"""Plots modelled vs fact values, prediction intervals and anomalies"""assert len(y_predict) == len(y)plt.figure(figsize=(15, 7))# plt.plot(y.index, y_predict, "g", label="prediction", linewidth=3.0)# plt.plot(y.index, y.values, label="actual", linewidth=1.0)plt.plot(y.index, y_predict, ls='-', c='#0072B2', label='predicted y')plt.plot(y.index, y.values, 'k.', label='y')if extra_plot is not None:# plt.plot(extra_plot.index, extra_plot.values, "y", label="future predict", linewidth=3.0)plt.plot(extra_plot.index, extra_plot.values, 'y', label='predicted y')if plot_intervals:lower = y_predict - intervalsupper = y_predict + intervals# plt.plot(y.index, lower, "r--", label="upper bond / lower bond", alpha=0.5)# plt.plot(y.index, upper, "r--", alpha=0.5)plt.fill_between(y.index, lower, upper, color='#0072B2', alpha=0.2, label='predicted upper/lower y')if extra_plot is not None:# plt.plot(extra_plot.index, extra_plot.values-intervals, "r--", label="upper bond / lower bond", alpha=0.5)# plt.plot(extra_plot.index, extra_plot.values+intervals, "r--", alpha=0.5)plt.fill_between(extra_plot.index, extra_plot.values-intervals, extra_plot.values+intervals,color='#0072B2', alpha=0.2, label='predicted upper/lower y')if plot_anomalies:anomalies_lower = y[y < lower]anomalies_upper = y[y > upper]# plt.plot(anomalies_lower.index, anomalies_lower.values, "ro", markersize=10, label="Anomalies(+)")# plt.plot(anomalies_upper.index, anomalies_upper.values, "ro", markersize=10, label="Anomalies(-)")plt.plot(anomalies_lower.index, anomalies_lower.values, "rX", label='abnormal points')plt.plot(anomalies_upper.index, anomalies_upper.values, "rX")error = mean_absolute_percentage_error(y_predict, y)plt.title("Mean absolute percentage error {0:.2f}%".format(error))plt.legend(loc="best")plt.tight_layout()plt.grid(True)plt.savefig(img_filename)def plot_arg_importance(model, X_train, img_filename="linear-cov.png"):"""Plots sorted coefficient values of the model"""coefs = pd.DataFrame(model.coef_, X_train.columns)coefs.columns = ["coef"]coefs["abs"] = coefs.coef.apply(np.abs)coefs = coefs.sort_values(by="abs", ascending=False).drop(["abs"], axis=1)plt.figure(figsize=(20, 12))coefs.coef.plot(kind='bar')plt.grid(True, axis='y')plt.hlines(y=0, xmin=0, xmax=len(coefs), linestyles='dashed')plt.savefig(img_filename)def code_mean(data, cat_feature, real_feature):"""Returns a dictionary where keys are unique categories of the cat_feature,and values are means over real_feature"""return dict(data.groupby(cat_feature)[real_feature].mean())def prepare_data(series, lag_start, lag_end, test_size, target_encoding=False, days_to_predict=2):"""series: pd.DataFramedataframe with timeserieslag_start: intinitial step back in time to slice target variableexample - lag_start = 1 means that the modelwill see yesterday's values to predict todaylag_end: intfinal step back in time to slice target variableexample - lag_end = 4 means that the modelwill see up to 4 days back in time to predict todaytest_size: floatsize of the test dataset after train/test split as percentage of datasettarget_encoding: booleanif True - add target averages to the dataset"""last_date = series["timestamp"].max()def make_future_date(periods, freq='D'):"""Simulate the trend using the extrapolated generative model.Parameters----------periods: Int number of periods to forecast forward.freq: Any valid frequency for pd.date_range, such as 'D' or 'M'.Returns-------pd.Dataframe that extends forward from the end of self.history for therequested number of periods."""dates = pd.date_range(start=last_date,periods=periods + 1,  # An extra in case we include startfreq=freq)dates = dates[dates > last_date]  # Drop start if equals last_datereturn dates[:periods]  # Return correct number of periodspredict_points = days_to_predict * 1440 # 1 day = 60*24 minutesfuture_dates = make_future_date(periods=predict_points, freq='T')df_future = pd.DataFrame({"timestamp": future_dates, "y": np.zeros(len(future_dates))})data = pd.concat([series, df_future])data.set_index("timestamp", drop=True, inplace=True)# data = pd.DataFrame(series.copy())# data.columns = ["y"]# print(data[:30])# lags of seriesfor i in range(lag_start, lag_end):data["lag_{}".format(i)] = data.y.shift(i)# print(data[:30])# datetime features# data.index = data.index.to_datetime()data["hour"] = data.index.hourdata["weekday"] = data.index.weekdaydata['is_weekend'] = data.weekday.isin([5, 6]) * 1test_index = int(len(series) * (1 - test_size))if target_encoding:# calculate averages on train set onlydata['weekday_average'] = list(map(code_mean(data[:test_index], 'weekday', "y").get, data.weekday))data["hour_average"] = list(map(code_mean(data[:test_index], 'hour', "y").get, data.hour))# drop encoded variables# data.drop(["hour", "weekday"], axis=1, inplace=True)# train-test splity = data.dropna().yX = data.dropna().drop(['y'], axis=1)total_size = len(X)# get the index after which test set startsX_train = X.iloc[:test_index]y_train = y.iloc[:test_index]X_test = X.iloc[test_index:total_size-predict_points]y_test = y.iloc[test_index:total_size-predict_points]X_predict = X.iloc[-predict_points:]y_predict = y.iloc[-predict_points:]return X_train, X_test, y_train, y_test, X_predict, y_predictdef mean_absolute_error(y_true, y_pred):abs_err = np.abs(y_true-y_pred)return np.mean(abs_err), np.std(abs_err)def calculate_intervals2(y_true, y_pred, scale):mae, std = mean_absolute_error(y_true, y_pred)return mae + scale * stddef calculate_intervals(lr, X_train, y_train, tscv, scale):cv = cross_val_score(lr, X_train, y_train,cv=tscv,scoring="neg_mean_squared_error")mae = cv.mean() * (-1)deviation = cv.std()return mae + scale * deviationdef linear_predict(data_frame, interval_scale=30, lag_start=60, lag_end=100, days_to_predict=2):"""predict time series data using linear model.:param data_frame:  input data frame. Must have timestamp and y columns. Also set index with timestamp.:param interval_scale:  interval range scale.:param lag_start:initial step back in time to slice target variableexample - lag_start = 1 means that the modelwill see yesterday's values to predict today:param lag_end:final step back in time to slice target variableexample - lag_end = 4 means that the modelwill see up to 4 days back in time to predict today:param days_to_predict: predicted days in future/:return:history_predict: history predicted value (pandas.Series)y_future: predicted value for future (pandas.Series)intervals: upper and lower range (float)."""assert "timestamp" in data_frame.columnsassert "y" in data_frame.columnsX_train, X_test, y_train, y_test, X_predict, y_predict = \prepare_data(data_frame, lag_start=lag_start, lag_end=lag_end, test_size=0.3, target_encoding=True, days_to_predict=days_to_predict)scaler = StandardScaler()X_train_scaled = scaler.fit_transform(X_train)X_test_scaled = scaler.transform(X_test)# for time-series cross-validation set 5 foldstscv = TimeSeriesSplit(n_splits=5)# lr = LinearRegression()lr = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, max_depth=1, random_state=666)# lr = LassoCV(cv=tscv)# lr = RidgeCV(cv=tscv)lr.fit(X_train_scaled, y_train)# plot_arg_importance(lr, X_train=X_train, img_filename="linear-cov.png")y_future = predict_future(lr, X_predict, y_predict, lag_start, lag_end, scaler)y = lr.predict(np.concatenate((X_train_scaled, X_test_scaled)))y_history = pd.concat([y_train, y_test])# intervals = calculate_intervals(lr, X_train, y_train, tscv, scale=interval_scale)intervals = calculate_intervals2(y_history, y, interval_scale)# anomalies_lower = y_history[y_history<y-intervals]# anomalies_upper = y_history[y_history>y+intervals]assert len(y_history.index) == len(y)return pd.Series(data=y, index=y_history.index, name="history_predict"), y_future, intervalsdef get_anoms(y_real, y_predict, intervals, lower_ratio=1.0, upper_ratio=1.0):"""calculat anomal point using predicted value and interval:param y_real:  real value (pandas.Series):param y_predict: predicted value (pandas.Series):param intervals:  upper and lower bound range (float):param lower_ratio: lower ratio you want to scale:param upper_ratio:  upper ratio you want scale:return:anoms_lower, anoms_upper (pandas.Series)"""anomalies_lower_index,anomalies_lower_val = [], []anomalies_upper_index,anomalies_upper_val = [], []for timestamp, expect_val in zip(y_predict.index, y_predict.values):real_val = y_real.loc[timestamp]if (expect_val-intervals) * lower_ratio > real_val:anomalies_lower_index.append(timestamp)anomalies_lower_val.append(real_val)if (expect_val+intervals) * upper_ratio < real_val:anomalies_upper_index.append(timestamp)anomalies_upper_val.append(real_val)return pd.Series(data=anomalies_lower_val, index=anomalies_lower_index),\pd.Series(data=anomalies_upper_val, index=anomalies_upper_index)def plot_history_and_future(y_predict, y_real, intervals, anomalies_lower, anomalies_upper, predicted_future, img_filename, need_lower=True):"""Plots modelled vs fact values, prediction intervals and anomalies"""assert len(y_predict) < len(y_real)plt.figure(figsize=(15, 7))plt.plot(y_predict.index, y_predict.values, ls='-', c='#0072B2', label='predicted y')plt.plot(y_real.index, y_real.values, 'k.', label='y')if need_lower:plt.fill_between(y_predict.index, y_predict.values - intervals, y_predict.values + intervals, color='#0072B2', alpha=0.2, label='predicted upper/lower y')else:plt.fill_between(y_predict.index, 0, y_predict.values + intervals, color='#0072B2', alpha=0.2, label='predicted upper/lower y')plt.plot(predicted_future.index, predicted_future.values, 'y', label='predicted y')if need_lower:plt.fill_between(predicted_future.index, predicted_future.values-intervals, predicted_future.values+intervals,color='#0072B2', alpha=0.2)else:plt.fill_between(predicted_future.index, 0, predicted_future.values+intervals,color='#0072B2', alpha=0.2)if need_lower:plt.plot(anomalies_lower.index, anomalies_lower.values, "rX", label='abnormal points')plt.plot(anomalies_upper.index, anomalies_upper.values, "rX")else:plt.plot(anomalies_upper.index, anomalies_upper.values, "rX", label="abnormal points")error = mean_absolute_percentage_error(y_predict, y_real)plt.title("Mean absolute percentage error {0:.2f}%".format(error))plt.legend(loc="best")plt.tight_layout()plt.grid(True)plt.savefig(img_filename)if __name__ == "__main__":data = pd.read_csv('raw_data.csv', usecols=['timestamp', 'count'])# input formatdata['timestamp'] = pd.to_datetime(data['timestamp'])data = data.sort_values('timestamp')data.rename(columns={'count': 'y'}, inplace=True)data.set_index("timestamp", drop=False, inplace=True)y_predict, y_future, intervals = linear_predict(data, interval_scale=5, lag_start=60, lag_end=100, days_to_predict=3)anomalies_lower, anomalies_upper = get_anoms(data['y'], y_predict, intervals)plot_history_and_future(y_predict=y_predict, y_real=data['y'], intervals=intervals, anomalies_lower=anomalies_lower,anomalies_upper=anomalies_upper, predicted_future=y_future, img_filename="linear.png", need_lower=True)  

修复了-1的问题:

for j in range(lag_end-1, lag_start, -1):

lag的bug。

此外使用梯度提升树模型做回归,目前看效果略好于其他模型,线性回归模型很健壮,但是在特殊情况下会出现网络流预测值为为负数的情形,根因还没有找到,而梯度提升树没有这个问题,但是GBT在数据平稳,预测应该是常数的时候会出现上升情形(线性回归也有这个问题,WHY???)。如下图所示数据情形:

转载于:https://www.cnblogs.com/bonelee/p/9904956.html

时间序列预测——线性回归(上下界、异常检测),异常检测时候历史数据的输入选择是关键,使用过去历史值增加模型健壮性...相关推荐

  1. 时间序列预测02:经典方法综述 自回归ARIMA/SRIMA 指数平滑法等

    机器学习和深度学习方法可以在具有挑战性的时间序列预测问题上取得不俗的表现.然而,在许多预测问题中,经典的方法,如SARIMA和指数平滑法(exponential smoothing ),容易优于更复杂 ...

  2. 干货 | 时间序列预测类问题下的建模方案探索实践

    作者 | 陆春晖 责编 | Carol 出品 | AI科技大本营(ID:rgznai100) 背景 时间序列类问题是数据分析领域中一类常见的问题,人们有时需要通过观察某种现象一段时间的状态,来判断其未 ...

  3. 序列每天从1开始_时间序列预测一

    什么是时间序列: 时间序列可以看作是普通的二维的无序的特征矩阵向时间空间的拓展,相对来说多了仅仅一个维度但也是非常重要的时间维度: 时间序列是按时间顺序进行的一系列观察,通常包括了连续性时间序列数据和 ...

  4. 【时序】TCCT:用于时间序列预测的紧耦合卷积 Transformer

    论文名称:TCCT: Tightly-coupled convolutional transformer on time series forecasting 论文下载:https://doi.org ...

  5. [时间序列预测]基于BP、RNN、LSTM、CNN-LSTM算法多特征(多影响因素)用电负荷预测[保姆级手把手教学]

    系列文章目录 深度学习原理-----线性回归+梯度下降法 深度学习原理-----逻辑回归算法 深度学习原理-----全连接神经网络 深度学习原理-----卷积神经网络 深度学习原理-----循环神经网 ...

  6. R 利用回归分析与时间序列预测北京市PM2.5

    注:代码全部在最后,数据来源UCI,链接如下: https://archive.ics.uci.edu/ml/datasets/Beijing+PM2.5+Data 摘要 现代社会科技进步,人们的生活 ...

  7. 【时间序列】时间序列预测方法总结(对应文章给出详细链接)

    来自 | 知乎 作者 | BINGO Hong 链接 | https://zhuanlan.zhihu.com/p/67832773 已经得到作者授权,仅作学术交流,请勿二次转载 1. 时间序列基本规 ...

  8. 如何用XGBoost做时间序列预测?

    ↑↑↑关注后"星标"Datawhale 每日干货 & 每月组队学习,不错过 Datawhale干货 来源:Jason Brownlee,整理:数据派THU 本文约3300字 ...

  9. 做时间序列预测有必要用深度学习吗?事实证明,梯度提升回归树媲美甚至超越多个DNN模型...

    来源:机器之心 本文约2600字,建议阅读9分钟 在时间序列预测任务上,你不妨试试简单的机器学习方法. 在深度学习方法应用广泛的今天,所有领域是不是非它不可呢?其实未必,在时间序列预测任务上,简单的机 ...

最新文章

  1. 基于vue的公共looploading组件(vue循环加载--组件)
  2. 光源时间_背光源缩短寿命的原因
  3. Selenium入门11 滚动条控制(通过js)
  4. 1、rbac权限组件-初识, 中间件校验1
  5. delphi trichviewedit 设置一行的段落_HTML中的文本与段落(3)
  6. 寻找点赞所需的URL
  7. java中什么是继承,和继承的接口的关系?
  8. TxDragon的训练5
  9. 股票历史数据下载梳理汇总(一)
  10. 解决office2016显示图标异常
  11. python的索引与切片
  12. MMA7455加速度传感器測量角度
  13. java每日一练(19_04_05)|逻辑表达式 !=、
  14. python tokenize怎么用_tokenize --- 对 Python 代码使用的标记解析器 — Python 3.9.1 說明文件...
  15. mysql键值_如何在MySQL中存储键值对?
  16. 说说 褥羊毛和薅羊毛的那些事
  17. oracle 电子书大全
  18. 彩虹代刷网免授权+精美WAP端源码
  19. ubifs 分区格式化方法
  20. 各项异性扩散滤波 -- OpenCV实现

热门文章

  1. NPM使用淘宝NPM镜像的使用方法汇总
  2. Selenium之定位浏览器弹窗方法汇总
  3. python中字典按键或键值排序
  4. bash参数及运算练习
  5. Linux下的USB总线驱动 mouse
  6. python列表不包含哪个内置函数_python 列表的推导器和内置函数
  7. 只调用一次_JavaScript运行机制 - 调用栈
  8. postgresql 参数替换 游标_postgresql动态游标使用案例
  9. xshell通过隧道连接_工作常见问题--如何解决xshell远程连接自动断开的问题
  10. oracle 怎么创建约束,Oracle创建约束