Пример #1
0
def discreetMethod(experimentGroup, testChildren, heights_groups,
                   t_heights_groups, printMode):
    if printMode:
        print("Discreet Method: ")

    # Find first epsilon for each formula
    epsilons = [x / 1000 for x in range(15, 305, 5)]
    eps1, score1 = findEpsilonByFormula(epsilons, experimentGroup,
                                        heights_groups, 1)
    eps2, score2 = findEpsilonByFormula(epsilons, experimentGroup,
                                        heights_groups, 2)
    eps3, score3 = findEpsilonByFormula(epsilons, experimentGroup,
                                        heights_groups, 3)
    eps4, score4 = findEpsilonByFormula(epsilons, experimentGroup,
                                        heights_groups, 4)
    printFirstEpsilonPerFormula(eps1, eps2, eps3, eps4, score1, score2, score3,
                                score4, printMode)

    # Find best epsilon for each formula
    problem1 = SearchEpsilon(eps1, score1, 1, experimentGroup, heights_groups)
    problem2 = SearchEpsilon(eps2, score2, 2, experimentGroup, heights_groups)
    problem3 = SearchEpsilon(eps3, score3, 3, experimentGroup, heights_groups)
    problem4 = SearchEpsilon(eps3, score3, 4, experimentGroup, heights_groups)
    bestEps1, bestScore1 = hill_climbing(problem1, 50).state
    bestEps2, bestScore2 = hill_climbing(problem2, 50).state
    bestEps3, bestScore3 = hill_climbing(problem3, 50).state
    bestEps4, bestScore4 = hill_climbing(problem4, 50).state
    if printMode:
        print("After local search: ")
        print("Formula number 1: Epsilon: ", bestEps1, ", score: ", bestScore1)
        print("Formula number 2: Epsilon: ", bestEps2, ", score: ", bestScore2)
        print("Formula number 3: Epsilon: ", bestEps3, ", score: ", bestScore3)
        print("Formula number 4: Epsilon: ", bestEps4, ", score: ", bestScore4)
        print()

    eps1, k_foldBestScore1 = findEpsilonByFormula([bestEps1], testChildren,
                                                  t_heights_groups, 1)
    eps2, k_foldBestScore2 = findEpsilonByFormula([bestEps2], testChildren,
                                                  t_heights_groups, 2)
    eps3, k_foldBestScore3 = findEpsilonByFormula([bestEps3], testChildren,
                                                  t_heights_groups, 3)
    eps4, k_foldBestScore4 = findEpsilonByFormula([bestEps4], testChildren,
                                                  t_heights_groups, 4)
    print("Results for best epsilons on test group:\n")
    printFirstEpsilonPerFormula(eps1, eps2, eps3, eps4, k_foldBestScore1,
                                k_foldBestScore2, k_foldBestScore3,
                                k_foldBestScore4, printMode)

    # Find best formula
    best_scores = [
        k_foldBestScore1, k_foldBestScore2, k_foldBestScore3, k_foldBestScore4
    ]
    best_epsilons = [bestEps1, bestEps2, bestEps3, bestEps4]
    bestScore = max(best_scores)
    best_formula = best_scores.index(bestScore)
    printBestFormula(best_formula, best_epsilons, bestScore, printMode)

    return best_formula, best_epsilons[best_formula]
def design(thread_id):
    # performer.initialize_files(performer.DATASET_DESIGN)
    architecture = performer.ARCHITECTURE
    # benchmark = 'combined'
    for benchmark in performer.BENCHMARKS:
        performer.reinitialize(thread_id, benchmark, 'latency', uniform(0, 8),
                               0)
        # performer.update_estimators(4)
        if architecture == 'mesh':
            graph = performer.generate_grid_graph()
        elif architecture == 'random':
            graph = performer.generate_random_graph()
        elif architecture == 'small_world':
            graph = performer.generate_small_world_graph()
        elif architecture == 'test':
            raw_topology = loadtxt('topology_test.tsv',
                                   int)[-performer.NODE_COUNT:,
                                        -performer.NODE_COUNT:]
            graph = from_numpy_matrix(raw_topology + 1)
            performer.process_graph(graph)
        elif architecture == 'optimum':
            optimization = Optimization(
                initial_state=performer.generate_small_world_graph())
            # optimization = Optimization(initial_state=performer.generate_grid_graph())
            final = hill_climbing(optimization)
            graph = final.state
        else:
            raise NameError('unknown architecture: ' + architecture)
        if graph != None:
            performer.update_database(performer.DATASET_DESIGN, architecture,
                                      graph)
    return
Пример #3
0
def design(thread_id):
    # performer.initialize_files(performer.DATASET_DESIGN)
    architecture = performer.ARCHITECTURE
    # benchmark = 'combined'
    for benchmark in performer.BENCHMARKS:
        performer.reinitialize(thread_id, benchmark, 'latency', uniform(0, 8), 0)
        # performer.update_estimators(4)
        if architecture == 'mesh':
            graph = performer.generate_grid_graph()
        elif architecture == 'random':
            graph = performer.generate_random_graph()
        elif architecture == 'small_world':
            graph = performer.generate_small_world_graph()
        elif architecture == 'test':
            raw_topology = loadtxt('topology_test.tsv', int)[-performer.NODE_COUNT:, -performer.NODE_COUNT:]
            graph = from_numpy_matrix(raw_topology + 1)
            performer.process_graph(graph)
        elif architecture == 'optimum':
            optimization = Optimization(initial_state=performer.generate_small_world_graph())
            # optimization = Optimization(initial_state=performer.generate_grid_graph())
            final = hill_climbing(optimization)
            graph = final.state
        else:
            raise NameError('unknown architecture: ' + architecture)
        if graph != None:
            performer.update_database(performer.DATASET_DESIGN, architecture, graph)
    return
Пример #4
0
                    else:
                        cols_diff = abs(queen - queen2)
                        rows_diff = abs(queen_row - queen2_row)

                        if cols_diff == rows_diff:
                            attacks += 1

        return -attacks

    def generate_random_state(self):
        state = []
        for queen in range(8):
            queen_row = randint(0, 7)
            state.append(queen_row)

        return tuple(state)


print("Hill climbing:")
fixed_initial_state = (0, 0, 0, 0, 0, 0, 0, 0)
problem = QueensProblem(fixed_initial_state)
result = hill_climbing(problem, iterations_limit=9999, viewer=WebViewer())
print(result.state, problem.value(result.state))

print("Hill climbing random restarts:")
problem = QueensProblem(None)
result = hill_climbing_random_restarts(problem,
                                       restarts_limit=999,
                                       iterations_limit=9999)
print(result.state, problem.value(result.state))
Пример #5
0
 def test_hill_climbing(self):
     result = hill_climbing(self.problem)
     self.assertEqual(result.state, GOAL)
Пример #6
0
 def solve_hillclimbing(self, iterations_limit=0, viewer=None):
     """
     résolution du problème
     """
     return hill_climbing(self, iterations_limit, viewer)
Пример #7
0
 def test_hill_climbing(self):
     result = hill_climbing(self.problem)
     self.assertEquals(result.state, GOAL)
Пример #8
0
def parametersTuning(f, X, c, function, ranges, hops, flag):
    problem = ParametersTuningLocalSearch(ranges, f, X, c, hops, function,
                                          flag)
    return hill_climbing(problem, 1000).state
Пример #9
0
def booleanAdaTuning(f, X, c, function, ranges):
    boolClass = False  # Boolean classification
    AB_hops = [1, 1, 0.05, 1, 5]
    problem = ParametersTuningLocalSearch(ranges, f, X, c, AB_hops, function, "AB", boolClass)
    return hill_climbing(problem, 1000).state
Пример #10
0
                                         initial_neightbours=k,
                                         initial_pca=alpha,
                                         pca_eps=args.ep,
                                         usar_pca=args.use_pca,
                                         memoize_pca=pca_memoize,
                                         print_log=args.print_log,
                                         logger=hpo_logger)

        from simpleai.search.viewers import BaseViewer
        visor = BaseViewer()

        if args.algorithm == "hill-climbing":
            print("Resolviendo con Hill Climbing")
            from simpleai.search.local import hill_climbing
            result = hill_climbing(knn_problem,
                                   viewer=visor,
                                   iterations_limit=args.iterations_limit)
            print("Encontramos: {}\nLuego de este camino: {}\n".format(
                result.state, result.path()))

        elif args.algorithm == "beam":
            print("Resolviendo con Beam")
            from simpleai.search.local import beam
            knn_problem = KNNRandomStateDecorator(knn_problem)
            result = beam(knn_problem,
                          viewer=visor,
                          beam_size=args.beam_size,
                          iterations_limit=args.iterations_limit)
            print("Encontramos: {}\nLuego de este camino: {}\n".format(
                result.state, result.path()))
def BattleSimulation(moves, player_1, player_2):
    initial = BattleState(100., 10., 10., 100., 10., 10.)
    return random.randint(5)

class FunSearch(SearchProblem):
    def __init__(self, initial_problem, player_1, player_2):
        SearchProblem.__init__(self, initial_state)
        self.player_1 = player_1
        self.player_2 = player_2
        
    def actions(self, state):
        return state.variations()

    def result(self, state, action):
        return action(state)

    def value(self, state):
        return BattleSimulation(state.moves, self.player_1, self.player_2)
   
    def generate_random_state(self):
        return FunState()

    #def heuristic(self, state):


problem = FunProblem(initial_state='')
result = hill_climbing(problem, iterations_limit=None)

print result.state
print result.path()
Пример #12
0
def sequentialMethod(experimentGroup, heights, testGroup, heights_groups,
                     printMode):
    if printMode:
        print("Sequential Method: ")
    epsilons = [x / 1000 for x in range(15, 305, 5)]

    # Find first epsilon for each formula
    WITHOUT_BINS = False
    eps1, score1 = findEpsilonByFormula(epsilons, experimentGroup, heights, 1,
                                        WITHOUT_BINS)
    eps2, score2 = findEpsilonByFormula(epsilons, experimentGroup, heights, 2,
                                        WITHOUT_BINS)
    eps3, score3 = findEpsilonByFormula(epsilons, experimentGroup, heights, 3,
                                        WITHOUT_BINS)
    eps4, score4 = findEpsilonByFormula(epsilons, experimentGroup, heights, 4,
                                        WITHOUT_BINS)
    printFirstEpsilonPerFormula(eps1, eps2, eps3, eps4, score1, score2, score3,
                                score4, printMode)

    # Find best epsilon for each formula
    problem1 = SearchEpsilon(eps1, score1, 1, experimentGroup, heights,
                             WITHOUT_BINS)
    problem2 = SearchEpsilon(eps2, score2, 2, experimentGroup, heights,
                             WITHOUT_BINS)
    problem3 = SearchEpsilon(eps3, score3, 3, experimentGroup, heights,
                             WITHOUT_BINS)
    problem4 = SearchEpsilon(eps4, score4, 4, experimentGroup, heights,
                             WITHOUT_BINS)
    bestEps1, bestScore1 = hill_climbing(problem1, 50).state
    bestEps2, bestScore2 = hill_climbing(problem2, 50).state
    bestEps3, bestScore3 = hill_climbing(problem3, 50).state
    bestEps4, bestScore4 = hill_climbing(problem4, 50).state
    if printMode:
        print("After local search: ")
        print("Formula number 1: Epsilon: ", bestEps1, ", score: ", bestScore1)
        print("Formula number 2: Epsilon: ", bestEps2, ", score: ", bestScore2)
        print("Formula number 3: Epsilon: ", bestEps3, ", score: ", bestScore3)
        print("Formula number 4: Epsilon: ", bestEps4, ", score: ", bestScore4)
        print()

    # Find best formula
    best_scores = [bestScore1, bestScore2, bestScore3, bestScore4]
    best_epsilons = [bestEps1, bestEps2, bestEps3, bestEps4]
    bestScore = max(best_scores)
    best_formula = best_scores.index(bestScore)
    printBestFormula(best_formula, best_epsilons, bestScore, printMode)

    # Calculate new ICT:
    newICT = calculateNewICT(experimentGroup, best_epsilons[best_formula],
                             best_formula + 1)  # List of (child, newICT)
    printCompareToPreviousICT(newICT, printMode)

    # Find the experts scores
    z_score = findScore([c.ICT_Z for c, p in newICT if c.ICT_Z != NA],
                        [c for c, p in newICT if c.ICT_Z != NA],
                        heights_groups, False)
    a_score = findScore([c.ICT_A for c, p in newICT if c.ICT_A != NA],
                        [c for c, p in newICT if c.ICT_A != NA],
                        heights_groups, False)
    printExpertsScores(z_score, a_score, printMode)

    # Calculate new ICT for children in the test Group
    testGroupICT = calculateNewICT(testGroup, best_epsilons[best_formula],
                                   best_formula + 1)  # List of (child, newICT)
    if printMode:
        print("Test Group ICT tagging info: ")
    printCompareToPreviousICT(testGroupICT, printMode)
Пример #13
0
    def heuristic(self, state):
        '''Returns an *estimation* of the distance from a state to the goal.
           We are using the manhattan distance.
        '''
        rows = string_to_list(state)

        distance = 0

        for number in '12345678e':
            row_n, col_n = find_location(rows, number)
            row_n_goal, col_n_goal = goal_positions[number]

            distance += abs(row_n - row_n_goal) + abs(col_n - col_n_goal)

        return distance


#print('GOAL', GOAL)
print('INITIAL', INITIAL)

#result = astar(EigthPuzzleProblem(INITIAL))
result = hill_climbing(EigthPuzzleProblem(INITIAL))

#print('result', result)

# if you want to use the visual debugger, use this instead:
# result = astar(EigthPuzzleProblem(INITIAL), viewer=WebViewer())
for action, state in result.path():
        print('Move number', action)
        print(state)