private void Start() { outputWriter = new StreamWriter(outputFileName); OpenFileDialog ofd = new OpenFileDialog(); ofd.Title = "Please Open Your Train File :"; ofd.InitialDirectory = Environment.CurrentDirectory; ofd.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"; if (ofd.ShowDialog().Value) { LoadData(ofd.FileName); } StartArima(train); StartSVM(getResidual().ToArray()); // now our hybrid model is created (Arima + SVM) List <float> results = new List <float>(); var arimaPred = arimaModel.Forecast(test.Length + NUMBER_OF_HYBRID_TEST); Queue <float> q = timeSeriGenerator.getLastInputForTesting(); for (int i = 0; i < NUMBER_OF_HYBRID_TEST; i++) { var valuePred = arimaPred[test.Length + i]; float residualPred = svmModel.Predict(new Matrix <float>(q.ToArray())); q.Dequeue(); q.Enqueue(residualPred); float resultValue = (float)valuePred + residualPred; results.Add(resultValue); } foreach (var result in results) { outputWriter.WriteLine(result); } outputWriter.WriteLine("\n\n"); outputWriter.WriteLine("MSE => " + MyErrorParameters.MSE(results.ToArray(), testHybrid)); outputWriter.WriteLine("ERROR% => " + MyErrorParameters.ERROR_Percent(results.ToArray(), testHybrid)); outputWriter.Flush(); outputWriter.Close(); MessageBox.Show( String.Format("Hybrid Model Created File {0} For Output Successfully Now , Please Check It Out .", outputFileName), "Hybrid Arima SVM Done", MessageBoxButton.OK, MessageBoxImage.Information); }
public double arimaModelFunction(int p, int d, int q, int errorMode) { NumericalVariable trainData = new NumericalVariable("trainData", train); // ARMA models (no differencing) are constructed from // the variable containing the time series data, and the // AR and MA orders. The following constructs an ARMA(2,1) // model: ArimaModel model = new ArimaModel(trainData, p, d, q); // The Compute methods fits the model. model.Compute(); // or to predict a specified number of values: Vector nextValues = model.Forecast(NUMBER_OF_TEST_CASES); switch (errorMode) { case 0: // MSE return(-1 * MyErrorParameters.MSE(nextValues.ToArray(), test)); case 1: // ERROR % return(-1 * MyErrorParameters.ERROR_Percent(nextValues.ToArray(), test)); } return(-9999999999); // a very bad fitness when error occured }
public IEnumerable <BasicDataset> Predict(IEnumerable <BasicDataset> datasets) { SplitSet(datasets, out IEnumerable <BasicDataset> trainingSet, out IEnumerable <BasicDataset> controlSet); int trainingCount = trainingSet.Count(), controlCount = controlSet.Count(); DateTime[] predictedDates = new DateTime[controlCount]; for (int i = 0; i < predictedDates.Length; ++i) { predictedDates[i] = controlSet.ElementAt(i).Date; } double[] closeValues = new double[trainingCount]; for (int i = 0; i < closeValues.Length; ++i) { closeValues[i] = (double)trainingSet.ElementAt(i).Close; } Vector <double> closeValuesVector = Vector.Create(closeValues); ArimaModel arima = ComputeBestValues(closeValuesVector, 1, 2, 1, 3, 3, 3); arima.EstimateMean = true; arima.Fit(); Vector <double> predictedValuesVector = arima.Forecast(controlCount); double[] predictedValues = predictedValuesVector.ToArray(); return(ConvertToDatasetRange(predictedDates, predictedValues)); }
private double getErrorOfArimaModel() { // or to predict a specified number of values: Vector nextValues = arimaModel.Forecast(numberOfTests); int selected = 0; Dispatcher.Invoke(new Action(() => selected = CompareComboBox.SelectedIndex)); switch (selected) { case 0: // MSE double mse = 0; for (int i = 0; i < numberOfTests; i++) { mse += Math.Pow(nextValues[i] - testArima[i], 2); } mse /= numberOfTests; return(-1 * mse); case 1: // ERROR % double errorPercent = 0; double sumTargets = 0; for (int i = 0; i < numberOfTests; i++) { errorPercent += Math.Abs(nextValues[i] - testArima[i]); sumTargets += Math.Abs(testArima[i]); } errorPercent /= sumTargets; return(-1 * errorPercent * 100); } return(-9999999999); // a very bad fitness when error occured }
public List <double> MakeArimaPrediction() { ArimaModel model = new ArimaModel(data, p, d, q); model.Fit(); Vector <double> nextValues = model.Forecast(predictionSize); return(new List <double>(nextValues).Select(x => System.Math.Round(x, 2)).ToList()); }
public overallForeCast getPPMonthlySalesForecast(int productProvider, int numPredictions, int value1 = 1, int value2 = 5) { var toreturn = new overallForeCast(); var monthlysales = (from c in db.salespermonths select c.sales.Value).ToList(); toreturn.previouse = Array.ConvertAll(monthlysales.ToArray(), c => (double)c); ArimaModel model = new ArimaModel(toreturn.previouse, value1, value2); model.Compute(); toreturn.predictions = Array.ConvertAll(model.Forecast(numPredictions).ToArray(), x => (double)x); return(toreturn); }
public overallForeCast PredictInsuranceTypeSales(int insuranceTypeID, int numPredictions, int value1 = 1, int value2 = 5) { var toreturn = new overallForeCast(); var monthlysales = (from c in db.insuranceproducttypemonthlysales where c.InsuranceType_ID == insuranceTypeID select c.sales.Value).ToList(); toreturn.previouse = Array.ConvertAll(monthlysales.ToArray(), c => (double)c); ArimaModel model = new ArimaModel(toreturn.previouse, value1, value2); model.Compute(); toreturn.predictions = Array.ConvertAll(model.Forecast(numPredictions).ToArray(), x => (double)x); return(toreturn); }
public overallForeCast PredictLocationSales(int productID, int locationID, int numPredictions, int value1 = 1, int value2 = 5) { var toreturn = new overallForeCast(); var monthlysales = (from c in db.monthlylocationsales where c.transactionLocation == locationID select c.sales.Value).ToList(); toreturn.previouse = Array.ConvertAll(monthlysales.ToArray(), c => (double)c); ArimaModel model = new ArimaModel(toreturn.previouse, value1, value2); model.Compute(); toreturn.predictions = Array.ConvertAll(model.Forecast(numPredictions).ToArray(), x => (double)x); return(toreturn); }
public List <double> getPredictions(predictions prevValueStr, int numPredictions, int value1 = 1, int value2 = 1) { List <double> toreturn = new List <double>(); var prevValues = prevValueStr.values.Split(',').Select(Int32.Parse).ToList(); toreturn.AddRange(Array.ConvertAll(prevValues.ToArray(), c => (double)c)); ArimaModel model = new ArimaModel(toreturn.ToArray(), value1, value2); model.Compute(); toreturn.AddRange(Array.ConvertAll(model.Forecast(numPredictions).ToArray(), x => (double)x)); return(toreturn); }
/// <summary> /// Performs validation using Root Mean-Squared Error given a time series (with forecast) and /// true values /// </summary> /// <param name="data"> UNMODIFIED. time series data being evaluated </param> /// <param name="testDataPercentage"> percentage of data to be used to evaluate as test set </param> /// <param name="params"> MODIFIED. parameter of the ARIMA model </param> /// <returns> a Root Mean-Squared Error computed from the forecast and true data </returns> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static double computeRMSEValidation(final double[] data, final double testDataPercentage, TimeSeries.Forecast.TimeSeries.Arima.struct.ArimaParams params) public static double computeRMSEValidation(double[] data, double testDataPercentage, ArimaParams @params) { int testDataLength = (int)(data.Length * testDataPercentage); int trainingDataEndIndex = data.Length - testDataLength; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final TimeSeries.Forecast.TimeSeries.Arima.struct.ArimaModel result = estimateARIMA(params, data, trainingDataEndIndex, data.length); ArimaModel result = estimateARIMA(@params, data, trainingDataEndIndex, data.Length); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final double[] forecast = result.forecast(testDataLength).getForecast(); double[] forecast = result.Forecast(testDataLength).Forecast; return(ComputeRMSE(data, forecast, trainingDataEndIndex, 0, forecast.Length)); }
private double getErrorOfArimaModel(int selected) { // or to predict a specified number of values: Vector nextValues = arimaModel.Forecast(numberOfTests); switch (selected) { case 0: // MSE return(-1 * MyErrorParameters.MSE(nextValues.ToArray(), testArima)); case 1: // ERROR % return(-1 * MyErrorParameters.ERROR_Percent(nextValues.ToArray(), testArima)); } return(-9999999999); // a very bad fitness when error occured }
public ProductForCast getProductSalesPredictions(int productID, int numPredictions, int value1 = 1, int value2 = 5) { var toreturn = new ProductForCast(); var pastSales = (from c in db.productsalespermonths where c.Product_ID == productID select c.sales.Value).ToList(); toreturn.productID = productID; toreturn.name = db.products.Find(productID).productName; toreturn.previouse = Array.ConvertAll(pastSales.ToArray(), x => (double)x); ArimaModel model = new ArimaModel(toreturn.previouse, value1, value2); model.Compute(); toreturn.predictions = Array.ConvertAll(model.Forecast(numPredictions).ToArray(), x => (double)x); return(toreturn); }
public double[][] Forecast(int days) { var openVector = Vector.Create(openValues); var closeVector = Vector.Create(closeValues); ArimaModel openModel = new ArimaModel(openVector, parameters[0], parameters[1], parameters[2]); ArimaModel closeModel = new ArimaModel(openVector, parameters[0], parameters[1], parameters[2]); openModel.Fit(); closeModel.Fit(); double[][] forecast = new double[2][]; forecast[0] = openModel.Forecast(days).ToArray(); // open forecast forecast[1] = closeModel.Forecast(days).ToArray(); // close forecast return(forecast); }
public double[] Arima(int forecast, double[] values) { Vector <double> tempValues = Vector.Create(values); //Find 'd'. var adf = new AugmentedDickeyFullerTest(values, 0); var p = adf.PValue; var acf = tempValues.AutocorrelationFunction(20); if (p > 0.05D) { p = 1; } tempValues = tempValues.Difference(); // An integrated model (with differencing) is constructed // by supplying the degree of differencing. Note the order // of the orders is the traditional one for an ARIMA(p,d,q) // model (p, d, q). var model = new ArimaModel(values, (int)p, 3, 3); model.EstimateMean = true; // The Compute methods fits the model. model.Fit(); //Predict a specified number of values: var nextValues = model.Forecast(forecast); //Cast to double[]. var castedNextValues = new double[nextValues.Length]; for (var i = 0; i < nextValues.Length; i++) { castedNextValues[i] = nextValues[i]; } // return castedNextValues; return(castedNextValues); }
public double[] ArimaTest(int lag) { // The time series data is stored in a numerical variable: var sunspots = Vector.Create(100.8, 81.6, 66.5, 34.8, 30.6, 7, 19.8, 92.5, 154.4, 125.9, 84.8, 68.1, 38.5, 22.8, 10.2, 24.1, 82.9, 132, 130.9, 118.1, 89.9, 66.6, 60, 46.9, 41, 21.3, 16, 6.4, 4.1, 6.8, 14.5, 34, 45, 43.1, 47.5, 42.2, 28.1, 10.1, 8.1, 2.5, 0, 1.4, 5, 12.2, 13.9, 35.4, 45.8, 41.1, 30.4, 23.9, 15.7, 6.6, 4, 1.8, 8.5, 16.6, 36.3, 49.7, 62.5, 67, 71, 47.8, 27.5, 8.5, 13.2, 56.9, 121.5, 138.3, 103.2, 85.8, 63.2, 36.8, 24.2, 10.7, 15, 40.1, 61.5, 98.5, 124.3, 95.9, 66.5, 64.5, 54.2, 39, 20.6, 6.7, 4.3, 22.8, 54.8, 93.8, 95.7, 77.2, 59.1, 44, 47, 30.5, 16.3, 7.3, 37.3, 73.9); //Find 'd'. AugmentedDickeyFullerTest adf = new AugmentedDickeyFullerTest(sunspots, 0); double d = adf.Statistic; // Console.WriteLine(d); // Console.WriteLine(adf.PValue); // An integrated model (with differencing) is constructed // by supplying the degree of differencing. Note the order // of the orders is the traditional one for an ARIMA(p,d,q) // model (p, d, q). // The following constructs an ARIMA(0,1,1) model: ArimaModel model = new ArimaModel(sunspots, 2, 1); model.EstimateMean = true; // The Compute methods fits the model. model.Fit(); //Predict a specified number of values: var nextValues = model.Forecast(5); //Cast to double[]. var castedNextValues = new double[nextValues.Length]; for (var i = 0; i < nextValues.Length; i++) { castedNextValues[i] = nextValues[i]; } return(castedNextValues); }
} // pure static class /// <summary> /// Raw-level ARIMA forecasting function. /// </summary> /// <param name="data"> UNMODIFIED, list of double numbers representing time-series with constant time-gap </param> /// <param name="forecastSize"> integer representing how many data points AFTER the data series to be /// forecasted </param> /// <param name="params"> ARIMA parameters </param> /// <returns> a ForecastResult object, which contains the forecasted values and/or error message(s) </returns> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static TimeSeries.Forecast.TimeSeries.Arima.struct.ForecastResult forecast_arima(final double[] data, final int forecastSize, TimeSeries.Forecast.TimeSeries.Arima.struct.ArimaParams params) public static ForecastResult forecast_arima(double[] data, int forecastSize, ArimaParams @params) { try { int p = @params.p; int d = @params.d; int q = @params.q; int P = @params.P; int D = @params.D; int Q = @params.Q; int m = @params.m; ArimaParams paramsForecast = new ArimaParams(p, d, q, P, D, Q, m); ArimaParams paramsXValidation = new ArimaParams(p, d, q, P, D, Q, m); // estimate ARIMA model parameters for forecasting ArimaModel fittedModel = ArimaSolver.estimateARIMA(paramsForecast, data, data.Length, data.Length + 1); // compute RMSE to be used in confidence interval computation double rmseValidation = ArimaSolver.computeRMSEValidation(data, ForecastUtil.testSetPercentage, paramsXValidation); fittedModel.RMSE = rmseValidation; ForecastResult forecastResult = fittedModel.Forecast(forecastSize); // populate confidence interval forecastResult.Sigma2AndPredicationInterval = fittedModel.Params; // add logging messages forecastResult.Log("{" + "\"Best ModelInterface Param\" : \"" + fittedModel.Params.summary() + "\"," + "\"Forecast Size\" : \"" + forecastSize + "\"," + "\"Input Size\" : \"" + data.Length + "\"" + "}"); // successfully built ARIMA model and its forecast return(forecastResult); } catch (Exception ex) { // failed to build ARIMA model throw new Exception("Failed to build ARIMA forecast: " + ex.Message); } }
public static async Task <ScalingState> ScalingFunction( [OrchestrationTrigger] DurableOrchestrationContext context, ILogger log) { log.LogScalingFunction("Get new input."); var scalingState = context.GetInput <ScalingState>(); log.LogScalingFunction($"Scaling for {scalingState.CurrentPartOfPeriod} part of period."); log.LogScalingFunction("Waiting for event from Metrics Collection"); if (scalingState.Wait) { var @event = await context.WaitForExternalEvent <MetricCollected>(nameof(MetricCollected)); log.LogScalingFunction($"Update current metrics data."); scalingState.AddMetric(@event.Metric); } log.LogScalingFunction($"Prepare ARIMA model. Autoregresive: {AutoregresiveParam}, Integration: {IntegrationParam}, Move Averrage: {MoveAverrageParam}"); var vectorMetricsData = Vector.Create(scalingState.MetricData.ToArray()); var model = new ArimaModel(vectorMetricsData, AutoregresiveParam, IntegrationParam, MoveAverrageParam); model.EstimateMean = true; log.LogScalingFunction("Fit ARIMA model."); model.Fit(); log.LogScalingFunction("Forecast capacity for rest period."); var period = MasterPerformMetricsCollector.Period - scalingState.CurrentPartOfPeriod - 1; var forecastedData = model.Forecast(period); log.LogScalingFunction("Calculate capacity"); var capacityPerDay = forecastedData.Select(z => CapacityHelpers.CalculateCapacity(z)).ToList(); var cost = capacityPerDay.Select(z => CapacityHelpers.CalculateCostOfCapacity(z)).Sum(); var restCost = scalingState.RestCost - cost; var division = (int)restCost / period; if (division >= 1) { var additionalMachine = division > 2 ? division / MasterPerformMetricsCollector.Q : 1; capacityPerDay = capacityPerDay.Select(z => z + additionalMachine).ToList(); restCost -= (additionalMachine * capacityPerDay.Count); } log.LogScalingFunction("Get capacity for part of period."); var capacity = capacityPerDay.First(); log.LogScalingFunction($"Capacity to set: {capacity}"); var action = new ScaleAction(capacity); await context.CallActivityAsync(nameof(Scaler), action); log.LogScalingFunction("Start new Scaling Function with new scaling state."); scalingState.NextPart(CapacityHelpers.CalculateCostOfCapacity(capacity)); context.ContinueAsNew(scalingState); return(scalingState); }
void Start() { var Et = new List <double>(); var Zt = new List <double>(); var Lt = new List <double>(); timeSeriGenerator = new TimeSeriGenerator <double>(); arimaLogger = new StreamWriter("Best_Hybrid_ArimaGALog.txt"); int numInp = 0; this.Dispatcher.Invoke(new Action(() => numInp = Int32.Parse(NumberOfInpTextBox.Text))); timeSeriGenerator.load(numInp); Dispatcher.Invoke(new Action(() => ActivityProgressBar.IsIndeterminate = true)); Dispatcher.Invoke(new Action(() => numberOfTests = Int32.Parse(OptimumTestTextBox.Text))); Dispatcher.Invoke(new Action(() => numberOfForecastTests = Int32.Parse(ForecastTestTextBox.Text))); MyTimeSeriForBestHybrid <double> myTimeSeriForBestHybrid = timeSeriGenerator.generateForBestHybrid(numberOfForecastTests); //maxGAIteretionInArima = 1000; //var train = new double[timeSeriGenerator.TimeSeri.Length - 5]; //var test = new double[5]; //for (int i = 0; i < train.Length; i++) //{ // train[i] = timeSeriGenerator.TimeSeri[i]; //} //for (int i = train.Length, j = 0; i < timeSeriGenerator.TimeSeri.Length; i++, j++) //{ // test[j] = timeSeriGenerator.TimeSeri[i]; //} //ArimaGA aga=new ArimaGA(); //aga.StartArima(train); //NumericalVariable timeSeriii = new NumericalVariable("timeSeriii", train); //arimaModel = new ArimaModel(timeSeriii, aga.bestP, aga.bestD, aga.bestQ); //arimaModel.Compute(); //var fv2 = arimaModel.Forecast(numberOfForecastTests); //double ea2 = MyErrorParameters.ERROR_Percent(fv2.ToArray(), test);) for (int i = 0; i < myTimeSeriForBestHybrid.part2.Count; i++) { StartArima(myTimeSeriForBestHybrid.part1.ToArray()); //// converting to double[] //double[] db = new double[myTimeSeriForBestHybrid.part1.Count]; //for (int j = 0; j < db.Length; j++) //{ // db[j] = myTimeSeriForBestHybrid.part1.ToArray()[j]; //} NumericalVariable timeSerii = new NumericalVariable("timeSerii", myTimeSeriForBestHybrid.part1.ToArray()); arimaModel = new ArimaModel(timeSerii, myBestP, myBestD, myBestQ); arimaModel.Compute(); var res = arimaModel.Forecast(1); float lt = (float)res[0]; Lt.Add(lt); double target = myTimeSeriForBestHybrid.part2[i]; double e = lt - target; Et.Add(e); myTimeSeriForBestHybrid.part1.Add(target); double mu = myTimeSeriForBestHybrid.part1.Average(); if (myBestD == 0) { Zt.Add(myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 1] - mu); } else if (myBestD == 1) { Zt.Add(myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 1] - myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 2] - mu); } else { Zt.Add(myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 1] - 2 * myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 2] + myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 3] - mu); } } ArimaModel EtArimaModel = new ArimaGA().GetBestModel(Et.ToArray()); ArimaModel ZtArimaModel = new ArimaGA().GetBestModel(Zt.ToArray()); int a = 0; SVM svm = new SVM(); //TimeSeriGenerator<double> gen = new TimeSeriGenerator<double>(); //gen.NumberOfInputVariables = Int32.Parse(NumberOfInpTextBox.Text); //gen.TimeSeri = Et.ToArray(); //var EtTimeSeries = gen.generate(); //gen = new TimeSeriGenerator<double>(); //gen.NumberOfInputVariables = Int32.Parse(NumberOfInpTextBox.Text); //gen.TimeSeri = Zt.ToArray(); //var ZtTimeSeries = gen.generate(); //// biaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Pair <int> bestAB = CreateComplexHybridModel(Et.ToArray(), Lt.ToArray(), Zt.ToArray()); double minErr = SVMComplexModelForBestModel(bestAB.First, bestAB.Second, Et.ToArray(), Lt.ToArray(), Zt.ToArray()); MessageBox.Show(bestAB.First + " , " + bestAB.Second + "\nMinError In Training Is => " + minErr, "Now Best M & N Found", MessageBoxButton.OK, MessageBoxImage.Asterisk); // --------------------------------- now our complex hybrid model is created ----------------------------------------------------------------- double mse = 0; double errorPercent = 0; double sumTargets = 0; if (myTimeSeriForBestHybrid.part1.Count != timeSeriGenerator.TimeSeri.Length - numberOfForecastTests) { MessageBox.Show("Input For Arima Model Is Not Completed", "ERROR", MessageBoxButton.OK, MessageBoxImage.Error); } // << CHECK HERE >> (FOR CHECKING PURPOSE ONLY , COMMENT HERE LATER) var forecastedVector = arimaModel.Forecast(numberOfForecastTests); double eoa = MyErrorParameters.ERROR_Percent(forecastedVector.ToArray(), myTimeSeriForBestHybrid.testCases.ToArray()); MessageBox.Show("Error Of Arima Is => " + eoa, "Arima Error", MessageBoxButton.OK, MessageBoxImage.Information); //maxGAIteretionInArima = 1000; //StartArima(myTimeSeriForBestHybrid.part1.ToArray()); //double[] dbb = new double[myTimeSeriForBestHybrid.part1.Count]; //for (int j = 0; j < dbb.Length; j++) //{ // dbb[j] = myTimeSeriForBestHybrid.part1.ToArray()[j]; //} //NumericalVariable timeSeriTest = new NumericalVariable("timeSerii", dbb); //arimaModel = new ArimaModel(timeSeriTest, myBestP, myBestD, myBestQ); //arimaModel.Compute(); StreamWriter hybridWriter = new StreamWriter(OUTPUT_FILE_NAME); List <double> results = new List <double>(); //double errorOfArima = MyErrorParameters.ERROR_Percent(forcastedVector.ToArray(), myTimeSeriForBestHybrid.testCases.ToArray()); //MessageBox.Show("Error Of Arima Is => " + errorOfArima, "Arima Error", MessageBoxButton.OK, // MessageBoxImage.Information); // --------------------------------------------------------------- int numOfInp = bestAB.First + bestAB.Second + 1; int rows = Et.Count - Math.Max(bestAB.First, bestAB.Second); float[,] inps = new float[rows, numOfInp]; double[] targs = new double[rows]; int y = bestAB.First; int z = bestAB.Second; int ll = 0; for (int o = 0; o < rows; o++) { if (y > z) { for (int j = 0; j < y; j++) { inps[o, j] = (float)Et[ll + j]; } inps[o, y] = (float)Lt[ll + y]; for (int j = 0; j < z; j++) { inps[o, y + j + 1] = (float)Zt[ll + y - z + j]; } targs[o] = timeSeriGenerator.TimeSeri[ll + y]; } else { for (int j = 0; j < y; j++) { inps[o, j] = (float)Et[ll + z - y + j]; } inps[o, y] = (float)Lt[ll + z]; for (int j = 0; j < z; j++) { inps[o, j + y + 1] = (float)Zt[ll + j]; } targs[o] = timeSeriGenerator.TimeSeri[ll + z]; } ll++; } float[,] trainInputs = new float[rows - numberOfTests, numOfInp]; float[] trainTargets = new float[rows - numberOfTests]; float[,] testInputs = new float[numberOfTests, numOfInp]; float[] testTargets = new float[numberOfTests]; int t = 0; for (; t < rows - numberOfTests; t++) { for (int j = 0; j < numOfInp; j++) { trainInputs[t, j] = inps[t, j]; } trainTargets[t] = (float)targs[t]; } for (int o = 0; t < rows; o++, t++) { for (int j = 0; j < numOfInp; j++) { testInputs[o, j] = inps[t, j]; } testTargets[o] = (float)targs[t]; } svmModelHybrid = new SVM(); SVM_KERNEL_TYPE bestKernelType = SVM_KERNEL_TYPE.RBF; double bestEps = 0.001; SVMParams p; Matrix <float> trainData = new Matrix <float>(trainInputs); Matrix <float> trainClasses = new Matrix <float>(trainTargets); p = new SVMParams(); p.KernelType = bestKernelType; p.SVMType = Emgu.CV.ML.MlEnum.SVM_TYPE.EPS_SVR; // for regression p.C = 1; p.TermCrit = new MCvTermCriteria(100, bestEps); p.Gamma = 1; p.Degree = 1; p.P = 1; p.Nu = 0.1; bool _trained = svmModelHybrid.TrainAuto(trainData, trainClasses, null, null, p.MCvSVMParams, 10); // --------------------------------------------------------------- for (int i = 0; i < numberOfForecastTests; i++) { float[,] inpTest = new float[bestAB.First + bestAB.Second + 1, 1]; int l = 0; for (int j = 0; j < bestAB.First; j++, l++) { inpTest[l, 0] = (float)Et[Et.Count - bestAB.First + j]; } inpTest[l++, 0] = (float)forecastedVector[i]; for (int j = 0; j < bestAB.Second; j++, l++) { inpTest[l, 0] = (float)Zt[Zt.Count - bestAB.Second + j]; } // injaaaaaaaaaaaaaaaaaaaa float result = svmModelHybrid.Predict(new Matrix <float>(inpTest)); results.Add(result); hybridWriter.WriteLine(result); double target = myTimeSeriForBestHybrid.testCases[i]; // preparing for next use in this for loop double resi = target - (float)forecastedVector[i]; // float resi = target - result; << CHECK HERE IMPORTANT >> Et.Add(resi); myTimeSeriForBestHybrid.part1.Add(target); double mu = myTimeSeriForBestHybrid.part1.Average(); if (myBestD == 0) { Zt.Add(myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 1] - mu); } else if (myBestD == 1) { Zt.Add(myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 1] - myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 2] - mu); } else //else if (bestD == 2) << CHECK HERE >> { Zt.Add(myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 1] - 2 * myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 2] + myTimeSeriForBestHybrid.part1[myTimeSeriForBestHybrid.part1.Count - 3] - mu); } } double _mse = MyErrorParameters.MSE(results.ToArray(), myTimeSeriForBestHybrid.testCases.ToArray()); double _errorPercent = MyErrorParameters.ERROR_Percent(results.ToArray(), myTimeSeriForBestHybrid.testCases.ToArray()); hybridWriter.WriteLine("\n\n\nMSE & ERROR% are =>\n\n{0} {1}", _mse, _errorPercent); hybridWriter.Flush(); hybridWriter.Close(); MessageBox.Show( String.Format( "Complex Hybrid Model Created File {0} For Output Successfully Now , Please Check It Out .", OUTPUT_FILE_NAME), "Hybrid SVM Arima Done", MessageBoxButton.OK, MessageBoxImage.Information); }