Added timeseries forecasting support implementing Holt-Winters with confidence interval

New API calls added
- ndpi_hw_init()
- ndpi_hw_add_value()
- ndpi_hw_free()
This commit is contained in:
Luca Deri
2021-02-08 19:10:25 +01:00
parent d9da752aa8
commit 732579b72b
4 changed files with 286 additions and 69 deletions
+35
View File
@@ -3733,6 +3733,40 @@ void hashUnitTest() {
/* *********************************************** */ /* *********************************************** */
void hwUnitTest() {
struct ndpi_hw_struct hw;
double v[] = { 10, 14, 8, 25, 16, 22, 14, 35, 15, 27, 218, 40, 28, 40, 25, 65 };
u_int i, j, num = sizeof(v) / sizeof(double);
u_int num_learning_points = 2;
u_int8_t trace = 0;
for(j=0; j<2; j++) {
assert(ndpi_hw_init(&hw, num_learning_points, j /* 0=multiplicative, 1=additive */, 0.9, 0.9, 0.1, 0.05) == 0);
if(trace)
printf("\nHolt-Winters %s method\n", (j == 0) ? "multiplicative" : "additive");
for(i=0; i<num; i++) {
double prediction, confidence_band;
double lower, upper;
int rc = ndpi_hw_add_value(&hw, v[i], &prediction, &confidence_band);
lower = prediction - confidence_band, upper = prediction + confidence_band;
if(trace)
printf("%2u)\t%.3f\t%.3f\t%.3f\t%.3f\t %s [%.3f]\n", i, v[i], prediction, lower, upper,
((rc == 0) || ((v[i] >= lower) && (v[i] <= upper))) ? "OK" : "ANOMALY",
confidence_band);
}
ndpi_hw_free(&hw);
}
exit(0);
}
/* *********************************************** */
/** /**
@brief MAIN FUNCTION @brief MAIN FUNCTION
**/ **/
@@ -3755,6 +3789,7 @@ int orginal_main(int argc, char **argv) {
/* Internal checks */ /* Internal checks */
// binUnitTest(); // binUnitTest();
hwUnitTest();
rsiUnitTest(); rsiUnitTest();
hashUnitTest(); hashUnitTest();
dgaUnitTest(); dgaUnitTest();
+7
View File
@@ -1397,6 +1397,13 @@ extern "C" {
/* ******************************* */ /* ******************************* */
int ndpi_hw_init(struct ndpi_hw_struct *hw, u_int16_t num_periods, u_int8_t additive_seeasonal,
double alpha, double beta, double gamma, float significance);
void ndpi_hw_free(struct ndpi_hw_struct *hw);
int ndpi_hw_add_value(struct ndpi_hw_struct *hw, const u_int32_t value, double *forecast, double *confidence_band);
/* ******************************* */
const char* ndpi_data_ratio2str(float ratio); const char* ndpi_data_ratio2str(float ratio);
void ndpi_data_print_window_values(struct ndpi_analyze_struct *s); /* debug */ void ndpi_data_print_window_values(struct ndpi_analyze_struct *s); /* debug */
+19
View File
@@ -1597,6 +1597,25 @@ typedef struct {
} ndpi_str_hash; } ndpi_str_hash;
/* **************************************** */
#define HW_HISTORY_LEN 4
struct ndpi_hw_struct {
struct {
u_int8_t use_hw_additive_seasonal;
double alpha, beta, gamma, ro;
u_int16_t num_season_periods; /* num of values of a season */
} params;
u_int32_t num_values;
double u, v, sum_square_error;
/* These two values need to store the signal history */
u_int32_t *y;
double *s;
};
/* **************************************** */ /* **************************************** */
#endif /* __NDPI_TYPEDEFS_H__ */ #endif /* __NDPI_TYPEDEFS_H__ */
+156
View File
@@ -898,3 +898,159 @@ float ndpi_rsi_add_value(struct ndpi_rsi_struct *s, const u_int32_t value) {
return(100. - (100. / (1. + relative_strength))); return(100. - (100. / (1. + relative_strength)));
} }
} }
/* *********************************************************** */
/* https://www.johndcook.com/blog/cpp_phi_inverse/ */
static double ndpi_rational_approximation(double t) {
// Abramowitz and Stegun formula 26.2.23.
// The absolute value of the error should be less than 4.5 e-4.
double c[] = { 2.515517, 0.802853, 0.010328 };
double d[] = { 1.432788, 0.189269, 0.001308 };
return(t - ((c[2]*t + c[1])*t + c[0]) / (((d[2]*t + d[1])*t + d[0])*t + 1.0));
}
static double ndpi_normal_cdf_inverse(double p) {
if(p <= 0.0 || p >= 1.0)
return(0); /* Invalid argument: valid range 0 < X < 1 */
if(p < 0.5) {
// F^-1(p) = - G^-1(p)
return -ndpi_rational_approximation( sqrt(-2.0*log(p)) );
} else {
// F^-1(p) = G^-1(1-p)
return ndpi_rational_approximation( sqrt(-2.0*log(1-p)) );
}
}
double ndpi_avg_inline(u_int32_t *v, u_int num) {
double avg = 0;
u_int i;
for(i=0; i<num; i++)
avg += v[i];
return(avg / (u_int32_t)num);
}
/* *********************************************************** */
/*
Initializes Holt-Winters with Confidence Interval
Input
hw: Datastructure to initialize and that needs tobe freed with ndpi_hw_free()
num_periods Number of observations of a season, or in ML-parlance the number of points that are required to make the forecast
additive If set to 1 will use the Holt-Winters additive seasonal (should be the default), otherwise the multiplicative seasonal.
alpha Level: specifies the coefficient for the level smoothing. Range 0..1. The higher α, the faster the method forgets old values
beta Trend: specifies the coefficient for the trend smoothing. Range 0..1.
gamma Seasonal: specifies the coefficient for the seasonal smoothing. Range 0..1. With gamma = 0, seaasonal correction is not used.
significance Significance level for the forecats sed for computing lower and upper bands. Range 0..1. Typical values 0.05 or less.
See https://en.wikipedia.org/wiki/Statistical_significance
NOTE (See https://otexts.com/fpp2/holt-winters.html)
The additive method is preferred when the seasonal variations are roughly constant through the series,
while the multiplicative method is preferred when the seasonal variations are changing proportional to the level of the series.
For learning more about timeseries forecasting see
https://www.real-statistics.com/time-series-analysis/basic-time-series-forecasting/
*/
int ndpi_hw_init(struct ndpi_hw_struct *hw,
u_int16_t num_periods, u_int8_t additive_seeasonal,
double alpha, double beta, double gamma, float significance) {
memset(hw, 0, sizeof(struct ndpi_hw_struct));
hw->params.num_season_periods = num_periods;
hw->params.alpha = alpha;
hw->params.beta = beta;
hw->params.gamma = gamma;
hw->params.use_hw_additive_seasonal = additive_seeasonal;
if((significance < 0) || (significance > 1)) significance = 0.05;
hw->params.ro = ndpi_normal_cdf_inverse(1 - (significance / 2.));
if((hw->y = (u_int32_t*)ndpi_calloc(hw->params.num_season_periods, sizeof(u_int32_t))) == NULL)
return(-1);
if((hw->s = (double*)ndpi_calloc(hw->params.num_season_periods, sizeof(double))) == NULL) {
free(hw->y);
return(-1);
}
return(0);
}
/* *********************************************************** */
/* Frees the memory allocated by ndpi_hw_init() */
void ndpi_hw_free(struct ndpi_hw_struct *hw) {
if(hw->y) ndpi_free(hw->y);
if(hw->s) ndpi_free(hw->s);
}
/* *********************************************************** */
/*
Returns the forecast and the band (forecast +/- band are the upper and lower values)
Input
hw: Datastructure previously initialized
value The value to add to the measurement
Output
forecast The forecasted value
confidence_band The value +/- on which the value should fall is not an anomaly
Return code
0 Too early: we're still in the learning phase. Output values are zero.
1 Normal processing: forecast and confidence_band are meaningful
*/
int ndpi_hw_add_value(struct ndpi_hw_struct *hw, const u_int32_t _value, double *forecast, double *confidence_band) {
if(hw->num_values < hw->params.num_season_periods) {
hw->y[hw->num_values++] = _value;
if(hw->num_values == hw->params.num_season_periods) {
double avg = ndpi_avg_inline(hw->y, hw->params.num_season_periods);
u_int i;
for(i=0; i<hw->params.num_season_periods; i++)
hw->s[i] = hw->y[i] / avg;
hw->u = _value / hw->s[hw->params.num_season_periods-1];
hw->v = 0;
}
*forecast = 0;
*confidence_band = 0;
return(0); /* Too early still training... */
} else {
u_int idx = hw->num_values % hw->params.num_season_periods;
double prev_u = hw->u;
double prev_v = hw->v;
double prev_s = hw->s[idx];
double value = (double)_value;;
double error;
hw->u = ((hw->params.alpha * value) / prev_s) + (1 - hw->params.alpha) * (hw->u + hw->v);
hw->v = (hw->params.beta * (hw->u - prev_u)) + ((1 - hw->params.beta) * hw->v);
hw->s[idx] = (hw->params.gamma * (value / hw->u)) + ((1 - hw->params.gamma) * prev_s);
hw->num_values++, idx = (idx + 1) % hw->params.num_season_periods;
if(hw->params.use_hw_additive_seasonal)
*forecast = (prev_u + prev_v) + prev_s;
else
*forecast = (prev_u + prev_v) * prev_s;
error = value - *forecast;
hw->sum_square_error += error * error;
*confidence_band = hw->params.ro * (sqrt(hw->sum_square_error / (hw->num_values - hw->params.num_season_periods)));
return(1); /* We're in business: forecast is meaningful now */
}
}