예제 #1
0
def darwin(networks: List[Network]) -> List[Network]:
    """Applique le modèle d'évolution dite "de Darwin" à une population de réseaux neuronaux

    Les réseaux sont triés selon leurs scores, puis les meilleurs d'entre eux sont utilisés pour
    créer d'autres réseaux, remplaçant les moins bons. Enfin, la plus grande partie des réseaux
    subit un phénomène de mutation altérant de manière aléatoire certaines de leurs valeurs.

    Parameters
    ----------
    networks:
        Liste des réseaux neuronaux sur lesquels appliquer l'évolution

    Returns
    -------
    List[Network]:
        Les réseaux unef fois édités
    """
    rank = sorted(networks, key=lambda net: net.score, reverse=True)  # first is best
    new_gen = [copy(rank[0]), copy(rank[1])]
    for _ in range(0, max(4, len(rank)-4), 2):
        new_gen += swap(copy(rank[0]), copy(rank[1]))
    if len(new_gen) < len(rank):
        new_gen += [Network(copy(networks[i].car)) for i in range(len(new_gen), len(rank))]
    for x in new_gen:
        x.car.abs_rotation = 0
    mutation(new_gen[2:])
    return new_gen[:len(networks)]
예제 #2
0
def read_network(input_dir='./input_data'):
    network = Network()
    _read_nodes(input_dir, network.node_list, network.node_id_to_no_dict,
                network.node_no_to_id_dict, network.zone_to_nodes_dict)
    _read_links(input_dir, network.node_list, network.link_list,
                network.node_id_to_no_dict, network.link_id_to_no_dict)
    network.update_node_size()
    network.update_link_size()
    return network
예제 #3
0
M2 = OC2 * N

p = .05
alpha = 1.
beta = .02
gamma = .12
sz = int(np.sqrt(N))

batch_size = 500
patch_size = (16, 16)

filename = 'images.pkl'
data = Data(filename, patch_size, seed=20150727)
X = data.get_batch(batch_size)

network = Network([Q1, Q2], [W1, W2], [theta1, theta2])
infer = TwoLayerInference(network)
Y1, Y2 = infer.activities(X)

from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
pp = PdfPages('plots.pdf')

#Find the 2 layer neurons that have the strongest connection to the 1 layer neurons
nL1 = 10
nL2 = 10
indxs = np.zeros((nL2, nL1))
for n in range(nL2):
    v = Q2[:, n]
    for c in range(nL1):
        idx = np.argmax(v)
예제 #4
0
파일: test.py 프로젝트: Dominik12345/seeds
import classes.Network as Net

import classes.Path as Path

#############################

N = Net.Network()

for i in range(1, 10):
    N.add_node('x' + str(i), 0)

N.add_error_node('x1')
N.add_error_node('x2')
N.add_observed_node('x6')
N.add_observed_node('x7')

N.add_dynamic_equation('x1', '-x1 + 0.5 * x9 ')
for i in range(2, 10):
    N.add_dynamic_equation('x' + str(i),
                           '-x' + str(i) + ' + 0.5 * x' + str(i - 1))

#############################

print(N.children('x2'))
print(N.parents('x2'))

#############################

P = Path.Path('x1')
P.append_node('x2')
예제 #5
0
#Testing file

from classes import Network, Neuron
from random import *

generatedinputs = []
expectedoutputs = []

net = Network([1, 2, 1])

#Higher numbers make it learn faster to a point
learn_rate = 8


def train(num_tests, num_backprop):

    populate_tests(num_tests)
    print("Original network values\n")
    check_network()

    for i in range(num_backprop):
        print("\nRun " + str(i) + "\n")
        backprop()
        check_network()


def test(num_tests):

    populate_tests(num_tests)
    print("Testing values\n")
    check_network()
예제 #6
0
def AI_loop(screen: pygame.Surface, circuit: dict) -> Network:
    """
    Boucle principale pour le mode automatique du programme

    Le but ici est d'entraîner des IA pour qu'elles soient le plus performant possible sur le
    circuit, donc en trouver au moins une qui arrive à la fin du circuit sans toucher aucune
    bordure.

    Parameters
    ----------
    screen:
        La fenêtre du programme
    circuit:
        Un dictionnaire contenant la liste des bordures représentant le circuit, ainsi que les deux
        points définissant la ligne de départ

    Returns
    -------
    Network:
        Le meilleur réseau de la dernière génération complétée
    """
    print("Astuce : Appuyez sur la touche R si une voiture tourne en rond\n")
    clock = pygame.time.Clock()
    small_font = pygame.font.SysFont('Arial', ceil(18 * SETTINGS.scale_avg))
    title_font = pygame.font.SysFont('Arial', ceil(30 * SETTINGS.scale_avg))
    dt = 1
    init_pos, init_angle = calc_starting_pos(circuit["point1"],
                                             circuit["point2"])
    cars = [
        Car(circuit["bordures"],
            color=SETTINGS.colors["cars"],
            starting_pos=init_pos,
            abs_rotation=init_angle) for _ in range(SETTINGS.cars_number)
    ]
    networks = [Network(c) for c in cars]
    networks[0].from_json(BackupManager().load()["network"])
    networks[0].car.color = "#00FF00"
    running = True

    increment = 0
    last_sorted_networks = None
    on_pause = False

    while running:
        increment += 1
        endgen = False
        cleanup_done = False
        start_time = time.time()
        while not endgen:

            temp = check_events()
            if temp == 1:
                endgen = True
            if temp == 2:
                return last_sorted_networks[
                    0] if last_sorted_networks is not None else None
            if temp == 3:
                on_pause = not on_pause

            screen.fill(SETTINGS.colors["background"])
            draw.circuit(screen, circuit["bordures"])
            draw.car(screen, (net.car for net in networks))

            delta = dt * FPS / 1000
            if not on_pause:
                # Gestion du mouvement de la voiture
                for net in networks:
                    if not net.dead:
                        net.update()
                        net.car.abs_rotation += SETTINGS.car_maniability * delta * net.direction

                        net.car.apply_vector(net.car.direction_vector() *
                                             net.engine * 2 *
                                             SETTINGS.scale_avg)
                        if not net.car.detection(screen,
                                                 SETTINGS.display_rays):
                            net.dead = True
                            net.car.death_time = time.time()

                survived = sum(1 for n in networks if not n.dead)
                if survived == 0:
                    endgen = True
                elif time.time() - start_time > 10 and not cleanup_done:
                    for net in networks:
                        if (not net.dead) and net.car.position[0] < 150:
                            net.dead = True
                            net.car.death_time = time.time()

            draw.general_stats(screen, small_font, clock, increment, survived,
                               start_time)
            draw.car_specs(screen, small_font, networks[0])
            draw.car_network(screen, small_font, networks[0])
            if on_pause:
                draw.pause_screen(screen, title_font)
                elapsed = dt / 1000
                start_time += elapsed
                for net in networks:
                    if not net.dead:
                        net.car.start_time += elapsed
            pygame.display.flip()
            dt = clock.tick(FPS)

        arrival = circuit["bordures"][-1]  # ligne d'arrivée
        # calcul des scores
        for net in networks:
            net.score = net.car.get_score()
            if net.car.distance_to_segment(arrival) <= 8:
                net.score += 300  # points bonus si la voiture a atteint la ligne d'arrivée
        average = round(sum([net.score for net in networks]) / len(networks))
        print(f"Génération N°{increment} terminée - score moyen : {average}")
        last_sorted_networks = copy.deepcopy(networks)

        # Darwin
        networks = darwin(networks)

        # Reset des réseaux/voitures
        for net in networks:
            net.dead = 0
            # net.car.position = [80, 130]
            net.car.color = SETTINGS.colors["cars"]
            net.car.reset()
        networks[0].car.color = SETTINGS.colors["main_car"]