CGC_Codes

stage 1 NN

Jun 7th, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.98 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3. using Encog.Engine.Network.Activation;
  4. using Encog.MathUtil.RBF;
  5. using Encog.ML.Data;
  6. using Encog.ML.Data.Basic;
  7. using Encog.ML.Data.Temporal;
  8. using Encog.Neural.Networks;
  9. using Encog.Neural.Networks.Layers;
  10. using Encog.Neural.Networks.Training;
  11. using Encog.Neural.Networks.Training.Propagation.SCG;
  12. using Encog.Neural.RBF;
  13. using Encog.Util.Arrayutil;
  14. using MathNet.Numerics.LinearAlgebra.Double;
  15. using QuantSys.Analytics;
  16. using QuantSys.Analytics.StatisticalModeling;
  17. using QuantSys.Util;
  18. using QuantSys.Visualization;
  19.  
  20. namespace QuantSys.MachineLearning.NeuralNetwork
  21. {
  22.     public class Stage1NeuralNetwork
  23.     {
  24.         private const double normalizeLo = -1;
  25.         private const double normalizeHi = 1;
  26.  
  27.         private readonly int WindowSize;
  28.         private readonly int iterations;
  29.         private readonly NormalizeArray normalizeArray;
  30.         private readonly double[] predictionData;
  31.         private readonly double[] trainingData;
  32.  
  33.         public double[] OutputData;
  34.         private double[] _normalizedPredictionData;
  35.         private double[] _normalizedTrainingData;
  36.         public BasicNetwork network;
  37.  
  38.         public double NextPrediction;
  39.         private int write;
  40.  
  41.         public Stage1NeuralNetwork(int windowSize, int iterations, double[] trainingData, double[] predictData)
  42.         {
  43.             WindowSize = windowSize;
  44.             this.iterations = iterations;
  45.             this.trainingData = trainingData;
  46.             predictionData = predictData;
  47.             normalizeArray = new NormalizeArray { NormalizedHigh = normalizeHi, NormalizedLow = normalizeLo };
  48.         }
  49.  
  50.         public void Execute(int write)
  51.         {
  52.             this.write = write;
  53.             _normalizedTrainingData = NormalizeData(trainingData);
  54.             _normalizedPredictionData = NormalizeData(predictionData);
  55.             network = CreateNetwork();
  56.             IMLDataSet training = GenerateTraining();
  57.             Train(training);
  58.             Predict();
  59.         }
  60.  
  61.  
  62.         public double[] NormalizeData(double[] data)
  63.         {
  64.             return normalizeArray.Process(data);
  65.         }
  66.  
  67.  
  68.         public BasicNetwork CreateNetwork()
  69.         {
  70.             var network = new BasicNetwork();
  71.             network.AddLayer(new BasicLayer(WindowSize));
  72.             network.AddLayer(new BasicLayer(new ActivationLinear(), true, WindowSize / 2 + 1));
  73.             network.AddLayer(new BasicLayer(1));
  74.             network.Structure.FinalizeStructure();
  75.             network.Reset();
  76.  
  77.             var rbfnetwork = new RBFNetwork(WindowSize, WindowSize / 2 + 1, 1, RBFEnum.Gaussian);
  78.  
  79.  
  80.             return network;
  81.         }
  82.  
  83.         public IMLDataSet GenerateTraining()
  84.         {
  85.             var result = new TemporalMLDataSet(WindowSize, 1);
  86.             var desc = new TemporalDataDescription(TemporalDataDescription.Type.Raw, true, true);
  87.             result.AddDescription(desc);
  88.  
  89.             for (int i = WindowSize; i < _normalizedTrainingData.Length; i++)
  90.             {
  91.                 var point = new TemporalPoint(1) { Sequence = i };
  92.                 point.Data[0] = _normalizedTrainingData[i];
  93.                 result.Points.Add(point);
  94.             }
  95.             result.Generate();
  96.             return result;
  97.         }
  98.  
  99.  
  100.         public void Train(IMLDataSet training)
  101.         {
  102.            
  103.             ITrain train = new ScaledConjugateGradient(network, training);
  104.  
  105.  
  106.             int epoch = 1;
  107.  
  108.             do
  109.             {
  110.                 train.Iteration();
  111.                 if ((epoch) % (iterations / 10) == 0) Console.Write(".");
  112.                 epoch++;
  113.             } while (epoch < iterations);
  114.         }
  115.  
  116.  
  117.         public void Predict()
  118.         {
  119.             double error = 0;
  120.             int c = 0;
  121.  
  122.             var d = new DenseMatrix(2, _normalizedPredictionData.Length - WindowSize);
  123.             int count = 0;
  124.             for (int i = WindowSize; i < _normalizedPredictionData.Length; i++)
  125.             {
  126.                 // calculate based on actual data
  127.                 IMLData input = new BasicMLData(WindowSize);
  128.                 for (int j = 0; j < input.Count; j++)
  129.                 {
  130.                     input.Data[j] = _normalizedPredictionData[(i - WindowSize) + j];
  131.                 }
  132.  
  133.                 IMLData output = network.Compute(input);
  134.                 double prediction = output.Data[0];
  135.  
  136.  
  137.                 error += Math.Pow((normalizeArray.Stats.DeNormalize(prediction) - predictionData[i]) / predictionData[i],
  138.                     2);
  139.                 c++;
  140.                 d[0, count] = predictionData[i];
  141.                 d[1, count] = normalizeArray.Stats.DeNormalize(prediction);
  142.                 count++;
  143.             }
  144.  
  145.             error /= c;
  146.             error = Math.Pow(error, .5);
  147.             Console.WriteLine(error);
  148.  
  149.             OutputData = d.Row(1).ToArray();
  150.  
  151.             string[] symbols = { "actual", "predicted" };
  152.             Visualize.GeneratePredictionGraph(symbols, d, new DateTime(), new TimeSpan(24, 0, 0),
  153.                 QSConstants.DEFAULT_DATA_FILEPATH + write + ".html");
  154.         }
  155.  
  156.  
  157.  
  158.         public void Predict(double[] newPredictData)
  159.         {
  160.             double error = 0;
  161.             int c = 0;
  162.  
  163.             double[] newNormalizedData = normalizeArray.Process(newPredictData);
  164.  
  165.             var d = new DenseMatrix(2, newNormalizedData.Length - WindowSize + 1, double.NaN);
  166.             int count = 0;
  167.             for (int i = WindowSize; i < newNormalizedData.Length; i++)
  168.             {
  169.                
  170.                 IMLData input = new BasicMLData(WindowSize);
  171.                 for (int j = 0; j < input.Count; j++)
  172.                 {
  173.                     input.Data[j] = newNormalizedData[(i - WindowSize) + j];
  174.                 }
  175.  
  176.                 IMLData output = network.Compute(input);
  177.                 double prediction = output.Data[0];
  178.  
  179.  
  180.                 error += Math.Pow((normalizeArray.Stats.DeNormalize(prediction) - newPredictData[i]) / newPredictData[i],
  181.                     2);
  182.                 c++;
  183.                 d[0, count] = newPredictData[i];
  184.                 d[1, count] = normalizeArray.Stats.DeNormalize(prediction);
  185.                 count++;
  186.             }
  187.  
  188.            
  189.  
  190.             var lastData = new double[WindowSize];
  191.             int count1 = 0;
  192.             for (int i = newNormalizedData.Length - WindowSize; i < newNormalizedData.Length; i++)
  193.             {
  194.                 lastData[count1++] = newNormalizedData[i];
  195.             }
  196.             IMLData input1 = new BasicMLData(WindowSize);
  197.  
  198.             for (int j = 0; j < input1.Count; j++)
  199.             {
  200.                 input1.Data[j] = lastData[j];
  201.             }
  202.  
  203.  
  204.             IMLData output1 = network.Compute(input1);
  205.             d[1, count] = normalizeArray.Stats.DeNormalize(output1.Data[0]);
  206.  
  207.  
  208.  
  209.  
  210.             error /= c;
  211.             error = Math.Pow(error, .5);
  212.             Console.WriteLine(error);
  213.  
  214.             OutputData = d.Row(1).ToArray();
  215.  
  216.             string[] symbols = { "actual", "predicted" };
  217.             Visualize.GeneratePredictionGraph(symbols, d, new DateTime(), new TimeSpan(24, 0, 0),
  218.                 QSConstants.DEFAULT_DATA_FILEPATH + write + ".html");
  219.  
  220.             Console.WriteLine("ST1 Correlation: " +
  221.                               StatisticsExtension.Correlation(
  222.                                   d.Row(0).ToArray().Take(d.ColumnCount - 1).ToArray().RawRateOfReturn(),
  223.                                   d.Row(1).ToArray().Take(d.ColumnCount - 1).ToArray().RawRateOfReturn()));
  224.         }
  225.  
  226.  
  227.         public double PredictNext(double[] inputData)
  228.         {
  229.  
  230.             double[] newNormalizedData = normalizeArray.Process(inputData);
  231.             IMLData input = new BasicMLData(WindowSize);
  232.             input.Data = newNormalizedData;
  233.             IMLData output1 = network.Compute(input);
  234.             double outputDenormalized = normalizeArray.Stats.DeNormalize(output1.Data[0]);
  235.             return outputDenormalized;
  236.         }
  237.  
  238.     }
  239. }
Advertisement
Add Comment
Please, Sign In to add comment