Beispiel #1
0
def main(args):
    rng = Random(args.seed)
    network_parameters = (105, 103, 100)
    trainer = Trainer(
        battleship_fitness,
        args.class_size,
        network_parameters,
        args.cream,
        rng,
        args.threads
    )

    if args.class_location:
        _, _, files = next(os.walk(args.class_location))
        networks = [os.path.join(args.class_location, f)
                    for f in files if f.endswith(".network")]
        trainer.stable = [Network.load_from_file(f) for f in networks]
    else:
        trainer.spawn_class()

    for n in range(args.rounds):
        print "Beginning round", n
        trainer.run_round(battleship_trainer)
        if args.output_location:
            generation_dir = os.path.join(
                args.output_location,
                "gen_{}".format(max(n.generation for n in trainer.stable))
            )
            os.makedirs(generation_dir)
            for network in trainer.stable:
                network.save_to_file(path=generation_dir)
            network, score = trainer.best
            network.save_to_file(filename="best_gen{}_{}.network".format(
                network.generation, score), path=args.output_location)
Beispiel #2
0
        turns += 1

    print network.name, "took", turns, "turns"

def battleship_trainer(network):
    games = 5

    print "Training", network.name, "for", games, "rounds"
    score = sum(map(lambda n: len(list(play_battleships(n))), [network] * games)) / games
    print network.name, "scored an average of", score
    return score


def battleship_fitness(score):
    return -score


if __name__ == "__main__":
    parameters = (105, 103, 100)
    print "Creating trainer"
    trainer = Trainer(lambda n: -n, 20, parameters, 3)
    print "Creating training function"
    print "Starting training"
    trainer.train(battleship_trainer, 5)

    best, score = trainer.best
    print "Winning network won in an average of", score, "turns"
    for move in play_battleships(best):
        print move
        print ""