Exemplo n.º 1
0
def run_optimization(max_eval, num_nodes, pop_size, offspring, trial_name, year):

    os_fold = os_sep()
    if not os.path.exists('results' + os_fold + year):
        os.makedirs('results' + os_fold + year)

    multiprocessing.freeze_support()
    problem = cequal()
    max_evaluations = max_eval


    algorithm = NSGAII(
        population_evaluator=MultiprocessEvaluator(num_nodes),
        problem=problem,
        population_size=pop_size,
        offspring_population_size=offspring,
        mutation=PolynomialMutation(probability= 0.2, distribution_index=20),
        crossover=SBXCrossover(probability=0.8, distribution_index=20),
        termination_criterion=StoppingByEvaluations(max_evaluations=max_evaluations),
        dominance_comparator=DominanceComparator()
    )

    algorithm.observable.register(ProgressBarObserver(max=max_evaluations))
    algorithm.observable.register(observer=BasicObserver())

    algorithm.run()
    print(os.getcwd())
    front = algorithm.get_result()

    print('Algorithm (continuous problem): ' + algorithm.get_name())
    print('Problem: ' + problem.get_name())
    print('Computing time: ' + str(algorithm.total_computing_time/3600))

    print_function_values_to_file(front, 'results' + os_fold + year + os_fold + 'OBJ_' + algorithm.get_name() + "_" + trial_name + '.txt')
    print_variables_to_file(front, 'results' + os_fold + year + os_fold + 'VAR_' + algorithm.get_name() + "_" + trial_name + '.txt')
Exemplo n.º 2
0
def Experiment(seedstrings):
    problem = MADM()
    seedset = []
    while len(seedset) <= N_seeds:
        for string in seedstrings:
            seed = problem.create_solution()
            seed.variables = string
            seedset.append(seed)

    max_evaluations = 100000
    #algorithm = SPEA2(
    algorithm = NSGAII(
        problem=problem,
        population_size=100,
        offspring_population_size=100,
        mutation=IntegerPolynomialMutation(probability=0.1),
        crossover=IntegerCrossover(probability=0.9),
        termination_criterion=StoppingByEvaluations(max=max_evaluations),
        population_generator=InjectorGenerator(seedset))

    resultsets = algorithm.run()
    process = []
    for g in range(len(resultsets)):
        process.append(get_non_dominated_solutions(resultsets[g]))

    return process, algorithm.get_result()
Exemplo n.º 3
0
def nsgaii_train(particoes, regras, instancias, classes):
    problem = MixedIntegerFloatProblem(particoes, regras, instancias, classes)

    max_evaluations = 10
    algorithm = NSGAII(
        problem=problem,
        population_size=10,
        offspring_population_size=10,
        mutation=CompositeMutation([IntegerPolynomialMutation(0.05, 20),
                                    IntegerPolynomialMutation(0.05, 20),
                                    PolynomialMutation(0.05, 20.0)]),
        crossover=CompositeCrossover([IntegerSBXCrossover(probability=0.95, distribution_index=20),
                                      IntegerSBXCrossover(probability=0.95, distribution_index=20),
                                      SBXCrossover(probability=0.95, distribution_index=20)]),
        termination_criterion=StoppingByEvaluations(max_evaluations=max_evaluations)
    )

    algorithm.run()
    front = get_non_dominated_solutions(algorithm.get_result())

    # Save results to file
    print_function_values_to_file(front, 'FUN.' + algorithm.label)
    print_variables_to_file(front, 'VAR.' + algorithm.label)

    print('Algorithm (continuous problem): ' + algorithm.get_name())
    print('Problem: ' + problem.get_name())
    print('Computing time: ' + str(algorithm.total_computing_time))

    minAcuracia = 0
    index = -1
    for i, f in enumerate(front):
        if minAcuracia > f.objectives[0]:
            minAcuracia =  f.objectives[0]
            index = i

    #for variable in front[index].variables:
       #print(variable.variables)


    particoes = problem.alterar_centroids(front[index].variables[2].variables)
    new_regras = problem.cromossomo_para_regras(front[index].variables[0].variables, front[index].variables[1].variables, problem.semente.qtdAntecedenteRegra, particoes)
    return particoes, new_regras
Exemplo n.º 4
0
    def train(self):
        problem = BinProblem(X=self.Xtrain,
                             Y=self.Ytrain,
                             kernel=self.kernel,
                             gamma=self.gamma,
                             degree=self.degree,
                             C=self.C,
                             coef0=self.coef0)

        max_evaluations = self.maxEvaluations
        algorithm = NSGAII(
            problem=problem,
            population_size=self.popsize,
            offspring_population_size=self.popsize,
            mutation=BitFlipMutation(probability=1.0 /
                                     np.shape(self.Xtrain)[0]),
            crossover=SPXCrossover(probability=1.0),
            termination_criterion=StoppingByEvaluations(max=max_evaluations))

        algorithm.run()
        front = algorithm.get_result()

        normed_matrix = normalize(
            list(map(lambda result: result.objectives, front)))

        scores = list(map(lambda item: sum(item), normed_matrix))
        solution = front[scores.index(min(scores))]

        self.instances = solution.variables[0]
        self.attributes = solution.variables[1]

        X = self.Xtrain[self.instances, :]
        X = X[:, self.attributes]
        Y = self.Ytrain[self.instances]

        self.model = SVC(gamma=self.gamma,
                         C=self.C,
                         degree=self.degree,
                         kernel=self.kernel)
        self.model.fit(X=X, y=Y)

        return self.model
Exemplo n.º 5
0
    def test_should_NSGAII_work_when_solving_problem_ZDT1_with_standard_settings(self):
        problem = ZDT1()

        max_evaluations = 25000

        algorithm = NSGAII(
            problem=problem,
            population_size=100,
            offspring_population_size=100,
            mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20),
            crossover=SBXCrossover(probability=1.0, distribution_index=20),
            termination_criterion=StoppingByEvaluations(max_evaluations=max_evaluations),
        )

        algorithm.run()
        front = algorithm.get_result()

        hv = HyperVolume(reference_point=[1, 1])
        value = hv.compute([front[i].objectives for i in range(len(front))])

        self.assertTrue(value >= 0.65)
Exemplo n.º 6
0
if __name__ == '__main__':
    problem = Rastrigin(10)

    max_evaluations = 50000
    algorithm = NSGAII(
        problem=problem,
        population_size=100,
        offspring_population_size=100,
        mutation=PolynomialMutation(probability=1.0 /
                                    problem.number_of_variables,
                                    distribution_index=20.0),
        crossover=SBXCrossover(probability=0.9, distribution_index=20.0),
        termination_criterion=StoppingByEvaluations(max=max_evaluations),
        dominance_comparator=DominanceComparator())

    algorithm.observable.register(observer=PrintObjectivesObserver(1000))

    algorithm.run()
    front = algorithm.get_result()

    # Save results to file
    print_function_values_to_file(
        front, 'FUN.' + algorithm.get_name() + "-" + problem.get_name())
    print_variables_to_file(
        front, 'VAR.' + algorithm.get_name() + "-" + problem.get_name())

    print('Algorithm (continuous problem): ' + algorithm.get_name())
    print('Problem: ' + problem.get_name())
    print('Computing time: ' + str(algorithm.total_computing_time))
Exemplo n.º 7
0
if __name__ == "__main__":
    problem = MixedIntegerFloatProblem(10, 10, 100, -100, -1000, 1000)

    max_evaluations = 25000
    algorithm = NSGAII(
        problem=problem,
        population_size=100,
        offspring_population_size=100,
        mutation=CompositeMutation([
            IntegerPolynomialMutation(0.01, 20),
            PolynomialMutation(0.01, 20.0)
        ]),
        crossover=CompositeCrossover([
            IntegerSBXCrossover(probability=1.0, distribution_index=20),
            SBXCrossover(probability=1.0, distribution_index=20),
        ]),
        termination_criterion=StoppingByEvaluations(
            max_evaluations=max_evaluations),
    )

    algorithm.run()
    front = get_non_dominated_solutions(algorithm.get_result())

    # Save results to file
    print_function_values_to_file(front, "FUN." + algorithm.label)
    print_variables_to_file(front, "VAR." + algorithm.label)

    print(f"Algorithm: {algorithm.get_name()}")
    print(f"Problem: {problem.get_name()}")
    print(f"Computing time: {algorithm.total_computing_time}")
Exemplo n.º 8
0
max_evaluations = 20000

algorithm = NSGAII(problem=problem,
                   population_size=100,
                   offspring_population_size=100,
                   mutation=PolynomialMutation(probability=1.0 /
                                               problem.number_of_variables,
                                               distribution_index=20),
                   crossover=SBXCrossover(probability=1.0,
                                          distribution_index=20),
                   termination_criterion=StoppingByEvaluations(
                       max_evaluations=max_evaluations))

algorithm.run()
solutions = algorithm.get_result()

from jmetal.lab.visualization.plotting import Plot
from jmetal.util.solution import get_non_dominated_solutions

front = get_non_dominated_solutions(solutions)

plot_front = Plot(title='Pareto front approximation', axis_labels=['x', 'y'])
plot_front.plot(front, label='OMOPSO-ZDT1')

# Save results
save = {
    0: 'Maximal profits',
    1: 'Maximal green hydrogen',
    2: 'Maximal electrolyser efficiency'
}
Exemplo n.º 9
0
    def train(self):
        problem = Ejemplo(X=self.Xtrain,
                          Y=self.Ytrain,
                          kernel=self.kernel,
                          gamma=self.gamma,
                          degree=self.degree,
                          C=self.C,
                          coef0=self.coef0)
        #problem.reference_front = read_solutions(filename='resources/reference_front/ZDT1.pf')

        max_evaluations = self.maxEvaluations
        algorithm = NSGAII(
            problem=problem,
            population_size=self.popsize,
            offspring_population_size=self.popsize,
            mutation=BitFlipMutation(probability=1.0 /
                                     np.shape(self.Xtrain)[0]),
            crossover=SPXCrossover(probability=1.0),
            termination_criterion=StoppingByEvaluations(max=max_evaluations))

        algorithm.observable.register(observer=ProgressBarObserver(
            max=max_evaluations))
        #algorithm.observable.register(observer=VisualizerObserver(reference_front=problem.reference_front))

        algorithm.run()
        front = algorithm.get_result()

        # Plot front
        plot_front = Plot(plot_title='Pareto front approximation',
                          reference_front=None,
                          axis_labels=problem.obj_labels)
        plot_front.plot(front,
                        label=algorithm.label,
                        filename=algorithm.get_name())

        # Plot interactive front
        plot_front = InteractivePlot(plot_title='Pareto front approximation',
                                     axis_labels=problem.obj_labels)
        plot_front.plot(front,
                        label=algorithm.label,
                        filename=algorithm.get_name())

        # Save results to file
        print_function_values_to_file(front, 'FUN.' + algorithm.label)
        print_variables_to_file(front, 'VAR.' + algorithm.label)
        print('Algorithm (continuous problem): ' + algorithm.get_name())

        # Get normalized matrix of results
        normed_matrix = normalize(
            list(map(lambda result: result.objectives, front)))

        # Get the sum of each objective results and select the best (min)
        scores = list(map(lambda item: sum(item), normed_matrix))
        solution = front[scores.index(min(scores))]

        self.instances = solution.variables[0]
        self.attributes = solution.variables[1]

        # Generate masks
        # Crop by characteristics and instances
        X = self.Xtrain[self.instances, :]
        X = X[:, self.attributes]
        Y = self.Ytrain[self.instances]

        self.model = SVC(gamma=self.gamma,
                         C=self.C,
                         degree=self.degree,
                         kernel=self.kernel)
        self.model.fit(X=X, y=Y)

        # write your code here
        return self.model
Exemplo n.º 10
0
    def train(self):
        problem = SVM_Problem(X=self.Xtrain, Y=self.Ytrain)
        #problem.reference_front = read_solutions(filename='resources/reference_front/ZDT1.pf')

        max_evaluations = self.maxEvaluations
        algorithm = NSGAII(
            problem=problem,
            population_size=self.popsize,
            offspring_population_size=self.popsize,
            mutation=PolynomialMutation(probability=1.0 /
                                        problem.number_of_variables,
                                        distribution_index=20),
            crossover=SBXCrossover(probability=1.0, distribution_index=20),
            termination_criterion=StoppingByEvaluations(max=max_evaluations))

        algorithm.observable.register(observer=ProgressBarObserver(
            max=max_evaluations))
        #algorithm.observable.register(observer=VisualizerObserver(reference_front=problem.reference_front))

        algorithm.run()
        front = algorithm.get_result()

        # Plot front
        plot_front = Plot(plot_title='Pareto front approximation',
                          reference_front=None,
                          axis_labels=problem.obj_labels)
        plot_front.plot(front,
                        label=algorithm.label,
                        filename=algorithm.get_name())

        # Plot interactive front
        plot_front = InteractivePlot(plot_title='Pareto front approximation',
                                     axis_labels=problem.obj_labels)
        plot_front.plot(front,
                        label=algorithm.label,
                        filename=algorithm.get_name())

        # Save results to file
        print_function_values_to_file(front, 'FUN.' + algorithm.label)
        print_variables_to_file(front, 'VAR.' + algorithm.label)
        print('Algorithm (continuous problem): ' + algorithm.get_name())

        print(
            "-----------------------------------------------------------------------------"
        )
        print('Problem: ' + problem.get_name())
        print('Computing time: ' + str(algorithm.total_computing_time))

        # Get normalized matrix of results
        normed_matrix = normalize(
            list(map(lambda result: result.objectives, front)))

        # Get the sum of each objective results and select the best (min)
        scores = list(map(lambda item: sum(item), normed_matrix))
        solution = front[scores.index(min(scores))]

        # Get our variables
        self.gamma = solution.variables[0]
        self.C = solution.variables[1]
        self.coef0 = solution.variables[2]
        self.degree = solution.variables[3]
        self.kernel = solution.variables[4]

        self.instances = solution.masks[0]
        self.attributes = solution.masks[1]

        # Select pick a random array with length of the variable
        X = self.Xtrain[self.instances, :]
        X = X[:, self.attributes]
        Y = self.Ytrain[self.instances]

        print(*front, sep=", ")

        # Contruct model
        self.model = SVM(Xtrain=X,
                         Ytrain=Y,
                         kernel=self.kernel,
                         C=self.C,
                         degree=self.degree,
                         coef0=self.coef0,
                         gamma=self.gamma,
                         seed=self.seed).train()

        print('Objectives: ', *solution.objectives, sep=", ")
        # write your code here
        return self.model