Exemple #1
0
def SexySnake(snakes):
    if (len(snakes) == 1):
        child = net.NeuralNet(snakes[0].topology)
        child.copy(snakes[0])

        child.mutate()
        snakes.append(child)
        return

    for i in range(1, len(snakes)):
        child = net.NeuralNet(snakes[0].topology)
        child.unflattenWeights(CrossOver(snakes[0], snakes[i]))
        child.mutate()
        snakes.append(child)
    return
Exemple #2
0
def nextGeneration(seeds):
    gen = []
    for i in range(population):
        seed = seeds[random.randint(0, len(seeds) - 1)]
        new_snake = net.NeuralNet(topology)
        new_snake.copy(seed)
        new_snake.mutate()
        gen.append(new_snake)

    return gen
Exemple #3
0
def loadNetwork(filename):
    import net
    with open(filename + '/params') as infile:
        params = json.load(infile)
    network = net.NeuralNet(params['numInputNeurons'] - 1,
                            params['numHiddenNeurons'] - 1,
                            params['numOutputNeurons'], params['learningRate'])
    hiddenWs = loadWeights(filename + '/_hidden_weights')
    outputWs = loadWeights(filename + '/_output_weights')
    for x in range(len(network.hiddenLayer)):
        network.hiddenLayer[x].weights = hiddenWs[x]
    for x in range(len(network.outputLayer)):
        network.outputLayer[x].weights = outputWs[x]
    return network
Exemple #4
0
def run(stdscr=None):
    game = Game()

    outfile = open('log.txt', 'w')
    debugfile = open('debug.txt', 'w')
    outfile.write(
        f'-------------------new log: {str(datetime.datetime.now())}\n\n')
    debugfile.write(
        f'-------------------new debug: {str(datetime.datetime.now())}\n\n')

    snakes = []
    for i in range(population):
        snake = net.NeuralNet(topology)
        snake.randomizeWeights()
        snakes.append(snake)

    for i in range(generations):
        scores = []
        outfile.write(f'start generation {i}')
        for snake in snakes:
            game.reset(8, 8)
            stdscr.clear()
            stdscr.addstr(0, 2 * width + 1, f'generation {i}')
            # stdscr.getch()
            agent = NEAgent(snake, stdscr, outfile, debugfile)
            # agent = NEAgent(snake, None, outfile, None)
            score, fullrun = game.play(agent, max_moves)
            scores.append(score)
            # print(f'{i}: {score}; ')
            if score > 2:
                # print(score)
                outfile.write(f'scored {score}! in gen {i}\n')
                outfile.write(fullrun)

        seeds = findWinners(snakes, scores)
        snakes = nextGeneration(seeds)
        # genetic_methods.LiveorDie(snakes, scores)
        # genetic_methods.SexySnake(snakes)

    outfile.close()
    debugfile.close()
Exemple #5
0
sys.path.insert(1, "/mnt/c/Users/Mayolp/AIFACT/snAIk")
import net
import genetic_methods
import numpy as np

#tids = []
#for i in range(1,5):
#    tids.append(threading.Thread(target=testsnake.Run, args=()))
#    tids[i-1].start()

#for i in tids:
#    i.join()
best_score = 0
snakes = []
for i in range(1, 5):
    network = net.NeuralNet([5, 3, 4])
    network.randomizeWeights()
    #print(network.weights)
    snakes.append(network)

while (best_score < 10 * 100):
    snake_counter = 0
    while (len(snakes) > 10):
        print("deleting snakes " + str(len(snakes)))
        if (np.random.random() > .50):
            snakes.pop(snake_counter)
            snake_counter -= 1
        snake_counter = (snake_counter + 1) % len(snakes)
    scores = []
    for i in range(0, len(snakes)):
        snake, score = testsnake.Run(snakes[i])
Exemple #6
0
# def printWeights(weights):
#     layer_counter = 1
#     for i in range(0, len(weights)):
#         print("Layer " + str(layer_counter) + ":")
#         node_counter = 1
#         for j in range(0, len(weights[i])):
#             print("\tNode " + str(node_counter) + ": ", end = "")
#             for k in range(0, len(weights[i][j])):
#                 print(weights[i][j][k], end = " ")
#             node_counter += 1
#             print()
#         layer_counter += 1
# --------------------------TESTING FEED FORWARD-------------------------------
print("--------------------------TESTING FEED FORWARD-------------------------------")
top = [4,3, 4] #layer 0 (input) has 4 nodes, layers 1 (a hidden) has 3 nodes
network = net.NeuralNet(top)
network.randomizeWeights()
# print(network.weights)


input = np.array(np.random.rand(1,4))
# input = [1,1 ,1]
# print(input)
input = input.transpose()
print(network.feedForward(input))
# print(network.weights)
network.randomizeWeights()
# print(network.weights)
print(network.feedForward(input))
print("-----------------------------------------------------------------------------",end = "\n\n")
# -----------------------------------------------------------------------------
Exemple #7
0
hiddenNodes = 250
numEpochs = 1
batchSize = 1
numExperiments = 1
######################################################################

if LetterSet:
    xData = []
    yData = []
    lYData = []
    lXData = []
    print "Letters Data Set ###############################"
    avgAcc = 0
    avgC = 0
    for y in range(0, numExperiments):
        net = nt.NeuralNet(63, hiddenNodes, 7, learningRate)
        expected = data.classOutputs()
        indices = data.labelIndex()
        correct = data.correctIndex()

        epochs = 1
        numShown = 0
        while epochs <= numEpochs:
            #shuffle(trainingSet)
            Fout = []
            for x in trainingSet:
                numShown += 1
                exp = expected[x.label]
                net.forwardPropagate(x)

                if numShown % batchSize == 0:
Exemple #8
0
hiddenNodes = 784
outputNodes = 10
numEpochs = 600
batchSize = 100
numExperiments = 1
######################################################################

xData = []
yData = []
lYData = []
lXData = []
print "MNIST ###############################"
avgAcc = 0
avgC = 0
for y in range(0, numExperiments):
    net = nt.NeuralNet(inputNodes, hiddenNodes, 10, learningRate)
    #indices = data.labelIndex()
    #correct = data.correctIndex()

    epochs = 1
    numShown = 0
    while epochs <= numEpochs:
        # shuffle(trainingSet)
        Fout = []
        for x in trainingSet:
            numShown += 1
            print 'Example: %d / %d' % (numShown, len(trainingSet))
            exp = expected[x.label]
            net.forwardPropagate(x)
            # Decaying learning rate.
            # if numShown % len(testingSet) / 7 == 0: