Ejemplo n.º 1
0
        public BasicMLData inputs()
        {
            var input = new BasicMLData(6);

            input[0] = location.Normalize(posX);
            input[1] = location.Normalize(posY);
            input[2] = speed.Normalize(velX);
            input[3] = speed.Normalize(velY);
            input[4] = location.Normalize(targetx);
            input[5] = location.Normalize(targety);

            return(input);
        }
        //public double Travel(ref int timeout, out int movesCnt)
        public double Travel(int timerTimeout, out int movesCnt)
        {
            MazeGame game = new MazeGame();

            game.InitGame(maze);
            game.traveler            = this;
            game.traveler.location.X = maze.StartingPosition.X;
            game.traveler.location.Y = maze.StartingPosition.Y;

            var recentOutcome = new MazeCycleOutcome();

            tmr.Interval = timerTimeout;
            tmr.Start();
            timeout  = 0;
            movesCnt = 0;

            while (!recentOutcome.GameOver && timeout == 0)
            {
                movesCnt++;
                var input = new BasicMLData(2);
                input[0] = xInput.Normalize(Convert.ToDouble(game.traveler.location.X));
                input[1] = yInput.Normalize(Convert.ToDouble(game.traveler.location.Y));

                IMLData output = network.Compute(input);

                double maxVal    = double.MinValue;
                int    direction = 0;
                for (int i = 0; i < output.Count; i++)
                {
                    if (output[i] > maxVal)
                    {
                        direction = i;
                        maxVal    = output[i];
                    }
                }
                recentOutcome = game.CycleMaze(direction);
                MazeCycleComplete?.Invoke(game.traveler.location.X, game.traveler.location.Y, recentOutcome.BumpedIntoWall);
            }

            tmr.Stop();

            var score = game.CalculateFinalScore(movesCnt);

            return(score);
        }
Ejemplo n.º 3
0
        public static BasicMLData getData(Pond pond)
        {
            var input = new BasicMLData(inputSize);

            input[0] = location.Normalize(-pond.sharkPos.X + pond.fishPos.X);
            input[1] = location.Normalize(-pond.sharkPos.Y + pond.fishPos.Y);

            /* input[2] = location.Normalize(pond.sharkPos.X - pond.fishPos.X);
             * input[3] = location.Normalize(pond.sharkPos.Y - pond.fishPos.Y);
             * input[4] = speed.Normalize(pond.fishVel.X - pond.sharkVel.X);
             * input[5] = speed.Normalize(pond.fishVel.Y - pond.sharkVel.Y);
             * input[6] = speed.Normalize(pond.sharkVel.X - pond.fishVel.X);
             * input[7] = speed.Normalize(pond.sharkVel.Y - pond.sharkVel.Y);
             * input[8] = pond.lastFish.X;
             * input[9] = pond.lastFish.Y;
             * input[10] = pond.lastShark.X;
             * input[11] = pond.lastShark.Y;*/

            return(input);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Called to notify the indicator that a bar has been received.
        /// </summary>
        /// <param name="packet">The packet received.</param>
        public override void NotifyPacket(IndicatorPacket packet)
        {
            long when = long.Parse(packet.Args[0]);

            if (_method == null)
            {
                if (_holder.Record(when, 2, packet.Args))
                {
                    _rowsDownloaded++;
                }
            }
            else
            {
                var input = new BasicMLData(Config.PredictWindow);

                const int fastIndex = 2;
                const int slowIndex = fastIndex + Config.InputWindow;

                for (int i = 0; i < 3; i++)
                {
                    double fast = CSVFormat.EgFormat.Parse(packet.Args[fastIndex + i]);
                    double slow = CSVFormat.EgFormat.Parse(packet.Args[slowIndex + i]);
                    double diff = _fieldDifference.Normalize((fast - slow) / Config.PipSize);
                    input[i] = _fieldDifference.Normalize(diff);
                }

                IMLData result = _method.Compute(input);

                double d = result[0];
                d = _fieldOutcome.DeNormalize(d);

                String[] args =
                {
                    "?",                                                           // line 1
                    "?",                                                           // line 2
                    CSVFormat.EgFormat.Format(d, EncogFramework.DefaultPrecision), // bar 1
                };                                                                 // arrow 2

                Link.WritePacket(IndicatorLink.PacketInd, args);
            }
        }
        public PlanogramOptResults ScorePilot()
        {
            PlanogramOptResults retVal = new PlanogramOptResults();

            var    shelves                 = new List <Shelf>();
            double totalMetricScore        = 0;
            int    slotNumber              = 0;
            Dictionary <int, int> itemDict = new Dictionary <int, int>();
            bool hasExceedMax              = false;

            for (int i = 0; i < simSettings.NumShelves; i++)
            {
                Shelf shelfInstance = new Shelf();
                for (int p = 0; p < simSettings.NumSlots; p++)
                {
                    var inputs = new BasicMLData(1);
                    inputs[0] = slotNormalizer.Normalize(slotNumber);

                    IMLData output = network.Compute(inputs);
                    int     index  = Convert.ToInt32(itemNormalizer.DeNormalize(output[0]));

                    Item itemReference = items[index];

                    if (!hasExceedMax)
                    {
                        hasExceedMax = !(CheckDuplicateItem(itemDict, index));
                    }

                    // with the item reference we will also have the Attributes which we need to calculate for the metrics
                    double itemMetricScore = PlanogramOptimizer.GetCalculatedWeightedMetrics(itemReference, simSettings);

                    // we add the item's metric score to totalMetricScore(which is our Session score in this case)
                    // notice that we multplied it with the numFacings since that is how many will also show up on the planogram
                    totalMetricScore += itemMetricScore;

                    shelfInstance.Add(itemReference, itemMetricScore);

                    slotNumber++;
                }

                shelves.Add(shelfInstance);
            }

            retVal.Shelves     = shelves;
            retVal.Score       = (hasExceedMax) ? 0 : totalMetricScore;
            retVal.TimeElapsed = DateTime.Now - simSettings.StartedOn;

            return(retVal);
        }
Ejemplo n.º 6
0
        public void Execute(IExampleInterface app)
        {
            // Normalize values with an actual range of (0 to 100) to (-1 to 1)
            var norm = new NormalizedField(NormalizationAction.Normalize,
                                           null, 100, 0, 1, -1);

            double x = 5;
            double y = norm.Normalize(x);

            Console.WriteLine(x + @" normalized is " + y);

            double z = norm.DeNormalize(y);

            Console.WriteLine(y + @" denormalized is " + z);
        }
Ejemplo n.º 7
0
        static void Normalization()
        {
            //Single value
            var    weightNorm        = new NormalizedField(NormalizationAction.Normalize, "Weights", ahigh: 40.0, alow: 50.0, nhigh: -1.0, nlow: 1.0);
            double normalizedValue   = weightNorm.Normalize(42.5);
            double denormalizedValue = weightNorm.DeNormalize(normalizedValue);

            //Array
            double[] weights     = new double[] { 40.0, 42.5, 43.0, 49.0, 50.0 };
            var      weightNorm2 = new NormalizeArray();

            weightNorm2.NormalizedHigh = 1.0;
            weightNorm2.NormalizedLow  = -1.0;
            double[] normalizedWeights = weightNorm2.Process(weights);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Process the individual training file.
        /// </summary>
        /// <param name="file">The training file to process.</param>
        /// <param name="output">The data set to output to.</param>
        protected void ProcessFile(string file, BufferedMLDataSet output)
        {
            var inputData = new BasicMLData(output.InputSize);
            var idealData = new BasicMLData(output.IdealSize);

            var csv = new ReadCSV(file, true, CSVFormat.English);

            while (csv.Next())
            {
                var    a     = new double[Config.InputWindow + 1];
                double close = csv.GetDouble(1);

                const int fastIndex = 2;
                const int slowIndex = fastIndex + Config.InputWindow;

                a[0] = close;
                for (int i = 0; i < 3; i++)
                {
                    double fast = csv.GetDouble(fastIndex + i);
                    double slow = csv.GetDouble(slowIndex + i);
                    double diff = _fieldDifference.Normalize((fast - slow) / Config.PipSize);
                    a[i + 1] = diff;
                }
                _window.Add(a);

                if (_window.IsFull())
                {
                    double max = (_window.CalculateMax(0, Config.InputWindow) - close) / Config.PipSize;
                    double min = (_window.CalculateMin(0, Config.InputWindow) - close) / Config.PipSize;

                    double o = Math.Abs(max) > Math.Abs(min) ? max : min;

                    a = _window.GetLast();
                    for (int i = 0; i < 3; i++)
                    {
                        inputData[i] = a[i + 1];
                    }

                    o            = _fieldOutcome.Normalize(o);
                    idealData[0] = o;

                    output.Add(inputData, idealData);
                }
            }
        }
        public Int16 Play(double[] inputs)
        {
            Int16 retVal = -1;

            var input = new BasicMLData(3);

            input[0] = xInput.Normalize(inputs[0]);
            input[1] = yInput.Normalize(inputs[1]);
            input[2] = bumpedIntoWallInput.Normalize(inputs[2]);

            IMLData output      = network.Compute(input);
            double  denormValue = output[0];
            double  normValue   = Math.Round(directionOutput.DeNormalize(denormValue));

            retVal = Convert.ToInt16(normValue);

            return(retVal);
        }
Ejemplo n.º 10
0
        public void LoadCSVFileTrainingRegg()
        {
            var path    = parameters.TrainFile;
            var csvRead = new ReadCSV(new FileStream(path, FileMode.Open), true, CSVFormat.DecimalPoint);
            var valuesX = new List <double[]>();
            var valuesY = new List <double[]>();

            while (csvRead.Next())
            {
                valuesX.Add(new double[1] {
                    csvRead.GetDouble(0)
                });
                valuesY.Add(new double[1] {
                    csvRead.GetDouble(1)
                });
            }
            csvRead.Close();

            var min = parameters.FunctionType == FunctionTypeEnum.Unipolar ? 0d : -1d;

            ArgNormalize = new NormalizedField[] { new NormalizedField(NormalizationAction.Normalize, "X", valuesX.Max(v => v[0]), valuesX.Min(v => v[0]), 1.0, min) };
            YNormalize   = new NormalizedField(NormalizationAction.Normalize, "Y", valuesY.Max(v => v[0]), valuesY.Min(v => v[0]), 1.0, min);
            for (int i = 0; i < valuesX.Count; i++)
            {
                valuesX[i][0] = ArgNormalize[0].Normalize(valuesX[i][0]);
                valuesY[i][0] = YNormalize.Normalize(valuesY[i][0]);
            }
            //if(parameters.FunctionType==FunctionTypeEnum.Bipolar)
            //        ansMeans = means[0];
            //ansfactor = factor[0];

            //ansMIn = Min[0];
            var trainSetCount = (int)((double)valuesX.Count * ((100.0 - 15) / 100));

            valuesX.Shuffle();
            valuesY.Shuffle();
            MyExtensions.ResetStableShuffle();

            TrainSet = new BasicNeuralDataSet(valuesX.Take(trainSetCount).ToArray(),
                                              valuesY.Take(trainSetCount).ToArray());
            ValidationSet = new BasicNeuralDataSet(valuesX.Skip(trainSetCount).ToArray(),
                                                   valuesY.Skip(trainSetCount).ToArray());
        }
        public int ScorePilot()
        {
            var sim = new LanderSimulator();

            while (sim.Flying)
            {
                var input = new BasicMLData(3);
                input[0] = _fuelStats.Normalize(sim.Fuel);
                input[1] = _altitudeStats.Normalize(sim.Altitude);
                input[2] = _velocityStats.Normalize(sim.Velocity);
                IMLData output = _network.Compute(input);
                double  value  = output[0];

                bool thrust;

                if (value > 0)
                {
                    thrust = true;
                    if (_track)
                    {
                        Console.WriteLine(@"THRUST");
                    }
                }
                else
                {
                    thrust = false;
                }

                sim.Turn(thrust);
                if (_track)
                {
                    Console.WriteLine(sim.Telemetry());
                }
            }

            CycleCount++;

            Outputs.Add(new EncogSimOut {
                Session = CycleCount, Score = sim.Score
            });

            return(sim.Score);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Normalize the array. Return the new normalized array.
        /// </summary>
        ///
        /// <param name="inputArray">The input array.</param>
        /// <returns>The normalized array.</returns>
        public double[] Process(double[] inputArray)
        {
            _stats = new NormalizedField();
            _stats.NormalizedHigh = _normalizedHigh;
            _stats.NormalizedLow  = _normalizedLow;

            foreach (double element in inputArray)
            {
                _stats.Analyze(element);
            }

            var result = new double[inputArray.Length];

            for (int i = 0; i < inputArray.Length; i++)
            {
                result[i] = _stats.Normalize(inputArray[i]);
            }

            return(result);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Normalize the array. Return the new normalized array.
        /// </summary>
        /// <param name="inputArray">The input array.</param>
        /// <param name="low">The low of the normalized array.</param>
        /// <param name="high">The high of the normalized array..</param>
        /// <returns>
        /// The normalized array.
        /// </returns>
        public double[] Process(double[] inputArray, int low, int high)
        {
            this.NormalizedHigh = high;
            this.NormalizedLow = low;
            _stats = new NormalizedField();
            _stats.NormalizedHigh = high;
            _stats.NormalizedLow = low;
            foreach (double element in inputArray)
            {
                _stats.Analyze(element);
            }

            var result = new double[inputArray.Length];

            for (int i = 0; i < inputArray.Length; i++)
            {
                result[i] = _stats.Normalize(inputArray[i]);
            }

            return result;
        }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            double error = 0.00001;

            double[][] XOR_Input =
            {
                new[] { 0.0, 0.0 },
                new[] { 1.0, 0.0 },
                new[] { 0.0, 1.0 },
                new[] { 1.0, 1.0 }
            };

            double[][] XOR_Ideal =
            {
                new[] { 0.0 },
                new[] { 1.0 },
                new[] { 1.0 },
                new[] { 0.0 }
            };

            var trainingSet = new BasicMLDataSet(XOR_Input, XOR_Ideal);

            BasicNetwork network = CreateNetwork();

            //var train = new Backpropagation(network, trainingSet, 0.7, 0.2);
            //var train = new ManhattanPropagation(network, trainingSet, 0.001);
            // var train = new QuickPropagation(network, trainingSet, 2.0);
            //var train = new ResilientPropagation(network, trainingSet);
            //var train = new ScaledConjugateGradient(network, trainingSet);
            var train = new LevenbergMarquardtTraining(network, trainingSet);

            int epoch = 0;

            do
            {
                train.Iteration();
                Console.WriteLine("Iteration No: {0}, Error: {1}", ++epoch, train.Error);
            }while (train.Error > error);

            foreach (var item in trainingSet)
            {
                var output = network.Compute(item.Input);
                Console.WriteLine("Input: {0}, {1} \tIdeal: {2} \t Actual: {3}", item.Input[0], item.Input[1], item.Ideal[0], output[0]);
            }

            Console.WriteLine("Training done.");
            Console.WriteLine("press any key to continue");
            Console.ReadLine();

            // normalized value
            var weightNorm = new NormalizedField(NormalizationAction.Normalize, "Weights", 50.0, 40.0, 1.0, -1.0);

            double normalizedValue   = weightNorm.Normalize(42.5);
            double denormalizedValue = weightNorm.DeNormalize(normalizedValue);

            Console.WriteLine("Normalized value: {0}", normalizedValue.ToString());
            Console.WriteLine("press any key to continue");
            Console.ReadLine();

            // normalized array
            double[] weights         = new double[] { 40.0, 42.5, 43.0, 49.0, 50.0 };
            var      weightNormArray = new NormalizeArray();

            weightNormArray.NormalizedHigh = 1.0;
            weightNormArray.NormalizedLow  = -1.0;
            double[] normalizedWeights = weightNormArray.Process(weights);

            foreach (var item in normalizedWeights)
            {
                Console.WriteLine("Normalized value: {0}", item.ToString());
            }
            Console.WriteLine("press any key to continue");
            Console.ReadLine();
        }
Ejemplo n.º 15
0
 public static double Normalize(double value, NormalizedField field)
 {
     return(field.Normalize(value));
 }