Ejemplo n.º 1
0
        private static void Run()
        {
            var       dataset        = new Dataset();
            var       nn             = new NeuralNetwork(dataset, 8); //8, 4
            const int populationSize = 10;
            const int iterations     = 1_000_000;
            var       crossovers     = new ICrossover[]
            {
                new BlxDoubleCrossover(),
                new ArithmeticCrossover(),
                new DiscreteUniformRecombination(),
                new OnePointCrossover(),
                new SimpleArithmeticRecombination()
            };
            var mutations = new IMutation[]
            {
                new GaussianAdditiveMutation(mutationProbability: 0.02, deviation: 0.2),
                new GaussianAdditiveMutation(mutationProbability: 0.02, deviation: 0.4),
                new GaussianSwapMutation(mutationProbability: 0.02, deviation: 0.5)
            };
            var desirability = new[] { 18.0, 4.0, 2.0 };

            var combinedCrossover = new CombinedCrossover(crossovers);
            var combinedMutation  = new CombinedMutation(mutations, desirability);

            var selection =
                new KTournamentSelection(nn.MeanSquareError, combinedCrossover, combinedMutation, k: 3);

            var parametersCount = nn.GetNumberOfRequiredParameters();
            var parameters      = new double[parametersCount];
            var doubleGa        = new DoubleGa(nn, parameters, parametersCount, populationSize, iterations);

            var bestNetworkParameters = doubleGa.FindBestIndividual(speedRun: true, selection).Representation;

            var success = 0;

            Console.WriteLine($"\nPrediction | Actual");
            foreach (var sample in dataset)
            {
                var prediction = nn.CalculateOutput(sample.X, sample.Y, bestNetworkParameters);
                var A          = prediction[0] < 0.5 ? 0 : 1;
                var B          = prediction[1] < 0.5 ? 0 : 1;
                var C          = prediction[2] < 0.5 ? 0 : 1;
                Console.WriteLine($"[{A} {B} {C}] | [{sample.A} {sample.B} {sample.C}]");

                if (A == sample.A && B == sample.B && C == sample.C)
                {
                    success++;
                }
            }

            Console.WriteLine(
                $"Prediction rate: {success}/{dataset.DatasetCount()} = {(double) success / dataset.DatasetCount() * 100}%");
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Executes a solver procedure.
        /// </summary>
        /// <param name="problem"></param>
        /// <returns></returns>
        internal override MaxTimeSolution Solve(MaxTimeProblem problem)
        {
            _customers = problem.Customers;

            //float[] solutions = OsmSharp.Math.VRP.Core.BestPlacement.CheapestInsertionHelper.CalculateBestValues(
            //    problem, _customers);

            generations = 0;

            _max_generations = 10000000;

            // calculate one tsp solution.
            //Tools.Math.TSP.ISolver tsp_solver = new OsmSharp.Math.TSP.EdgeAssemblyGenetic.EdgeAssemblyCrossOverSolver(_population, _stagnation,
            //         new OsmSharp.Math.TSP.Genetic.Solver.Operations.Generation._3OptGenerationOperation(),
            //          new OsmSharp.Math.TSP.Genetic.Solver.Operations.CrossOver.EdgeAssemblyCrossover(30,
            //                 OsmSharp.Math.TSP.Genetic.Solver.Operations.CrossOver.EdgeAssemblyCrossover.EdgeAssemblyCrossoverSelectionStrategyEnum.SingleRandom,
            //                 true));
            //IRoute tsp_solution = tsp_solver.Solve(new OsmSharp.Routing.VRP.NoDepot.MaxTime.TSPPlacement.TSPProblem(
            //    problem));
            // initialize the generation.
            IGenerationOperation <MaxTimeSolution, MaxTimeProblem, Fitness> generation =
                //new SolverGenerationOperation(new TSPPlacement.TSPPlacementSolver<ResolvedType>(
                //    this.Router, this.Max, this.DeliveryTime, tsp_solution));
                new OsmSharp.Routing.VRP.NoDepot.MaxTime.Genetic.Generation.RandomBestPlacement();
            //new SolverGenerationOperation(new CheapestInsertionSolverWithImprovements<ResolvedType>(
            //    this.Router, this.Max, this.DeliveryTime, 5, 0.1f, true, 0.1f, false, 1f, null, null));
            //new SolverGenerationOperation(new CheapestInsertionSolverWithImprovements<ResolvedType>(
            //    this.Router, this.Max, this.DeliveryTime, 5, 0.1f, true, 0.1f, true, 1f));

            // initialize the crossover.
            ICrossOverOperation <MaxTimeSolution, MaxTimeProblem, Fitness> cross_over =
                new OsmSharp.Routing.VRP.NoDepot.MaxTime.Genetic.CrossOver.RouteExchangeOperation();

            // initialize the mutation.
            //IMutationOperation<MaxTimeSolution, MaxTimeProblem, Fitness> mutation =
            //    new VehicleMutation();

            List <IMutationOperation <MaxTimeSolution, MaxTimeProblem, Fitness> > mutators =
                new List <IMutationOperation <MaxTimeSolution, MaxTimeProblem, Fitness> >();

            mutators.Add(new VehicleMutation());
            //mutators.Add(new ThreeOptMutation());
            //mutators.Add(new RedivideRouteMutation());
            mutators.Add(new RoutePartExchangeMutation());
            if (_probabilities == null)
            {
                _probabilities = new List <double>();
                _probabilities.Add(0.2);
                _probabilities.Add(0.6);
                _probabilities.Add(0.2);
            }

            CombinedMutation <MaxTimeSolution, MaxTimeProblem, Fitness> mutation = new CombinedMutation <MaxTimeSolution, MaxTimeProblem, Fitness>(
                StaticRandomGenerator.Get(),
                mutators,
                _probabilities);


            SolverSettings settings = new SolverSettings(_stagnation, _population, _max_generations,
                                                         _elitism_percentage, _cross_percentage, _mutation_percentage);
            MaxTimeProblem genetic_problem = problem;// new MaxTimeProblem(max,  problem, solutions);
            Solver <MaxTimeSolution, MaxTimeProblem, Fitness> solver =
                new Solver <MaxTimeSolution, MaxTimeProblem, Fitness>(genetic_problem, settings,
                                                                      new TournamentBasedSelector <MaxTimeSolution, MaxTimeProblem, Fitness>(5, 0.5),
                                                                      mutation,   //new ThreeOptMutation(),
                                                                      cross_over, // new RouteExchangeOperation(), //new RouteExchangeOperation(), //new RouteExchangeAndVehicleOperation(), // Order1CrossoverOperation()
                                                                      generation, //new RandomBestPlacement(),//new RandomGeneration(), //new RandomBestPlacement(),
                                                                      new FitnessCalculator());

            solver.NewFittest += new Solver <MaxTimeSolution, MaxTimeProblem, Fitness> .NewFittestDelegate(solver_NewFittest);

            //solver.NewGeneration += new Solver<MaxTimeSolution, Problem, Fitness>.NewGenerationDelegate(solver_NewGeneration);
            Individual <MaxTimeSolution, MaxTimeProblem, Fitness> solution = solver.Start(null);
            //this.solver_NewFittest(solution);

            MaxTimeSolution routes = solution.Genomes;

            long ticks_after = DateTime.Now.Ticks;

            StringBuilder sizes = new StringBuilder();

            foreach (int size in routes.Sizes)
            {
                sizes.Append(size);
                sizes.Append(" ");
            }

            StringBuilder weights = new StringBuilder();

            foreach (double weight in solution.Fitness.Weights)
            {
                weights.Append(weight.ToString(CultureInfo.InvariantCulture));
                weights.Append(" ");
            }

            return(routes);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Executes a solver procedure.
        /// </summary>
        /// <param name="problem"></param>
        /// <returns></returns>
        internal override MaxTimeSolution Solve(MaxTimeProblem problem)
        {
            //            _customers = problem.Customers;

            //float[] solutions = OsmSharp.Math.VRP.Core.BestPlacement.CheapestInsertionHelper.CalculateBestValues(
            //    problem, _customers);

            generations = 0;

            _max_generations = 10000000;

            // calculate one tsp solution.
            //Tools.Math.TSP.ISolver tsp_solver = new OsmSharp.Math.TSP.EdgeAssemblyGenetic.EdgeAssemblyCrossOverSolver(_population, _stagnation,
            //         new OsmSharp.Math.TSP.Genetic.Solver.Operations.Generation._3OptGenerationOperation(),
            //          new OsmSharp.Math.TSP.Genetic.Solver.Operations.CrossOver.EdgeAssemblyCrossover(30,
            //                 OsmSharp.Math.TSP.Genetic.Solver.Operations.CrossOver.EdgeAssemblyCrossover.EdgeAssemblyCrossoverSelectionStrategyEnum.SingleRandom,
            //                 true));
            //IRoute tsp_solution = tsp_solver.Solve(new OsmSharp.Routing.VRP.NoDepot.MaxTime.TSPPlacement.TSPProblem(
            //    problem));
            // initialize the generation.
            IGenerationOperation<MaxTimeSolution, MaxTimeProblem, Fitness> generation =
                //new SolverGenerationOperation(new TSPPlacement.TSPPlacementSolver<ResolvedType>(
                //    this.Router, this.Max, this.DeliveryTime, tsp_solution));
                new OsmSharp.Routing.VRP.NoDepot.MaxTime.Genetic.Generation.RandomBestPlacement();
            //new SolverGenerationOperation(new CheapestInsertionSolverWithImprovements<ResolvedType>(
            //    this.Router, this.Max, this.DeliveryTime, 5, 0.1f, true, 0.1f, false, 1f, null, null));
            //new SolverGenerationOperation(new CheapestInsertionSolverWithImprovements<ResolvedType>(
            //    this.Router, this.Max, this.DeliveryTime, 5, 0.1f, true, 0.1f, true, 1f));

            // initialize the crossover.
            ICrossOverOperation<MaxTimeSolution, MaxTimeProblem, Fitness> cross_over =
                new OsmSharp.Routing.VRP.NoDepot.MaxTime.Genetic.CrossOver.RouteExchangeOperation();

            // initialize the mutation.
            //IMutationOperation<MaxTimeSolution, MaxTimeProblem, Fitness> mutation =
            //    new VehicleMutation();

            List<IMutationOperation<MaxTimeSolution, MaxTimeProblem, Fitness>> mutators =
                new List<IMutationOperation<MaxTimeSolution, MaxTimeProblem, Fitness>>();
            mutators.Add(new VehicleMutation());
            //mutators.Add(new ThreeOptMutation());
            //mutators.Add(new RedivideRouteMutation());
            mutators.Add(new RoutePartExchangeMutation());
            if (_probabilities == null)
            {
                _probabilities = new List<double>();
                _probabilities.Add(0.2);
                _probabilities.Add(0.6);
                _probabilities.Add(0.2);
            }

            CombinedMutation<MaxTimeSolution, MaxTimeProblem, Fitness> mutation = new CombinedMutation<MaxTimeSolution, MaxTimeProblem, Fitness>(
                StaticRandomGenerator.Get(),
                mutators,
                _probabilities);

            SolverSettings settings = new SolverSettings(_stagnation, _population, _max_generations,
                _elitism_percentage, _cross_percentage, _mutation_percentage);
            MaxTimeProblem genetic_problem = problem;// new MaxTimeProblem(max,  problem, solutions);
            Solver<MaxTimeSolution, MaxTimeProblem, Fitness> solver =
                new Solver<MaxTimeSolution, MaxTimeProblem, Fitness>(genetic_problem, settings,
                new TournamentBasedSelector<MaxTimeSolution, MaxTimeProblem, Fitness>(5, 0.5),
                mutation, //new ThreeOptMutation(),
                cross_over, // new RouteExchangeOperation(), //new RouteExchangeOperation(), //new RouteExchangeAndVehicleOperation(), // Order1CrossoverOperation()
                generation, //new RandomBestPlacement(),//new RandomGeneration(), //new RandomBestPlacement(),
                new FitnessCalculator());
            solver.NewFittest += new Solver<MaxTimeSolution, MaxTimeProblem, Fitness>.NewFittestDelegate(solver_NewFittest);
            //solver.NewGeneration += new Solver<MaxTimeSolution, Problem, Fitness>.NewGenerationDelegate(solver_NewGeneration);
            Individual<MaxTimeSolution, MaxTimeProblem, Fitness> solution = solver.Start(null);
            //this.solver_NewFittest(solution);

            MaxTimeSolution routes = solution.Genomes;

            long ticks_after = DateTime.Now.Ticks;

            StringBuilder sizes = new StringBuilder();
            foreach (int size in routes.Sizes)
            {
                sizes.Append(size);
                sizes.Append(" ");
            }

            StringBuilder weights = new StringBuilder();
            foreach (double weight in solution.Fitness.Weights)
            {
                weights.Append(weight.ToString(CultureInfo.InvariantCulture));
                weights.Append(" ");
            }

            return routes;
        }