def teste_do_controle():
    #input size é o numero dos sensores do robo. nesse caso, serão oito
    #output size é o numero de destinos que o robo pode escolher. nesse caso serão quatro.
    n = neural.Network(inputSize=8, hiddenSize=10, outputSize=4)
    x, y = controle.gerar_posicao_inicial()
    inter = controle.Bilinear(x_inicial=-20,
                              x_final=20,
                              y_inicial=-20,
                              y_final=20,
                              delta=1,
                              psy=controle.fi)
    controle.controle(neural=n,
                      interpolacao=inter,
                      xlinha=controle.xlinha_interpolacao,
                      ylinha=controle.ylinha_interpolacao,
                      deltah=1,
                      obstaculos=None,
                      nome_do_arquivo='isso_eh_um_teste')
Exemple #2
0
class Application(GameApplication):

    AI = neural.Network(
        neural.layout.FeedForward(
            (5, neural.neuron.Input),
            (2, neural.neuron.Output),
            *[(3, neural.neuron.Hidden)] * 1,
            *[(3, neural.neuron.Recurrent)] * 3,
            *[(3, neural.neuron.Hidden)] * 1,
        ))

    def initialize(self, app: engine.core.Application):
        super().initialize(app)
        engine.instantiate(engine.component.Event(self.close_event, "WINDOW"),
                           id=False)

        app.window._master.title(f"Dinosaur")
        app.world.system(engine.ecs.systems.Render, True)
        app.world.add_system(PhysBodySystem(), "PHYSICS")
        app.world.add_system(engine.ecs.systems.FPS(), "POST")

        setting_collision = app.setting.collision()
        setting_collision.matrix.make(
            setting_collision.layers.set("Player", 10),
            setting_collision.layers.set("Enviroment", 11),
            setting_collision.layers.set("Obstacle", 12),
        )
        setting_collision.matrix.compile()

        setting_render = app.setting.render()
        setting_render.layers["Player"] = 110
        setting_render.compile()

        manager = StateManager()
        engine.instantiate(manager, ObstacleManager(),
                           engine.component.Event(manager.restart))

        engine.instantiate(  # Player
            PlayerController(manager),
            PlayerControllerAI(manager) if self.AIState >= self.AIState.ACTIVE
            else PlayerControllerInput(),
            PhysBody(0.06),
            engine.component.Collider(
                engine.physics.collider.Rectangle,
                engine.component.Transform(scl=engine.Vector(50, 100)),
                "Player"),
            engine.component.Render(engine.render.Polygon.Quad(50, 100),
                                    layer="Player"),
            transform=engine.component.Transform(
                engine.Vector(GameApplication.width // 16,
                              GameApplication.height // 2)))

        engine.instantiate(  # Floor
            engine.component.Collider(
                engine.physics.collider.Rectangle,
                engine.component.Transform(
                    scl=engine.Vector(GameApplication.width, 20)),
                "Enviroment"),
            engine.component.Render(
                engine.render.Polygon.Quad(GameApplication.width, 20)),
            transform=engine.component.Transform(
                engine.Vector(GameApplication.width // 2, FLOOR + 10)))

        engine.instantiate(  # FPS
            engine.component.FPS(),
            engine.component.Render(engine.render.Text("FPS"), True),
            transform=engine.component.Transform(
                engine.Vector(GameApplication.width - 20, 8)))

    def close_event(self, event: engine.event.KeyPress):
        if event.dispatch(engine.event.KeyPress
                          ) and event.key is engine.input.Key.ESCAPE:
            engine.app().event(engine.event.WindowClose())
networks = []
end_price = candles[-1].closing

epochs = 20
random_samples = 5
top_samples = 5
cooldown = 1.0
intra_cooldown = 0.01

for epoch in range(epochs):

    todo = []

    random_networks = []
    for _ in range(random_samples):
        network = neural.Network(parameters, [], 2)
        todo.append(network)
        random_networks.append(network)

    top = min(top_samples, len(networks))
    for index in range(0, top):
        top_network = networks[index][1]
        for random_network in random_networks:
            mix = neural.combine_networks(top_network, random_network)
            todo.append(mix)

    print('testing', len(todo), 'networks (', epoch, '/', epochs, ')')
    for network in todo:
        start = 0
        end = batch
        funds = 1000.0
Exemple #4
0
#X = (hours studying, hours sleeping), y = score on test, xPredicted = 4 hours studying & 8 hours sleeping (input data for prediction)
#X = np.array(([3, 8, 10, 32, 45], [5, 7, 21, 25, 37], [6, 15, 20, 30, 38], [2, 4, 8, 27, 50],[8, 16, 24, 26, 35]), dtype=int)
#y = np.array(( [5, 7, 21, 25, 37], [6, 15, 20, 30, 38], [2, 4, 8, 27, 50], [7, 17, 29, 37, 45],[8, 16, 24, 26, 35]), dtype=int)
#xPredicted = np.array(([7, 17, 29, 37, 45]), dtype=int)

X = np.array(([3, 8, 10, 32, 45],[6, 15, 20, 30, 38],[7, 17, 29, 37, 45],[9, 18, 32, 38, 46]), dtype=int)
y = np.array(([5, 7, 21, 25, 37], [2, 4, 8, 27, 50], [8, 16, 24, 26, 35],[1, 3, 33, 40, 45]), dtype=int)
xPredicted = np.array(([3, 12, 36, 44, 45]), dtype=int)

# scale units
X = X/50 # maximum of X array
xPredicted = xPredicted/50 # maximum of xPredicted (our input data for the prediction)
y = y/50 # max test score is 100


NN = neural.Network(5,5,25)
for i in range(10000): # trains the NN 1,000 times
  #print ("# " + str(i) + "\n")
  #print ("Input (scaled): \n" + str(X))
  #print ("Actual Output: \n" + str(y))
  #print ("Predicted Output: \n" + str(NN.forward(X)))
  #print ("Loss: \n" + str(np.mean(np.square(y - NN.forward(X))))) # mean sum squared loss
  #print ("\n")
  NN.train(X, y)


NN.saveWeights()
NN.predict(xPredicted)


def get_fingerprint(key = []):
Exemple #5
0
for index in range(1, candle_end):
    if candles[index + 1].closing > candles[index].closing and candles[
            index - 1].closing > candles[index].closing:
        signal_out.append([1.0, 0.0, 0.0])
    elif candles[index].closing > candles[
            index + 1].closing and candles[index].closing > candles[index -
                                                                    1].closing:
        signal_out.append([0.0, 1.0, 0.0])
    else:
        signal_out.append([0.0, 0.0, 1.0])

parameters_per_period = 5
period_range = 24  # 672 (28 days of hours)
parameters = parameters_per_period * period_range
end_price = candles[-1].closing
network = neural.Network(parameters, [parameters], 3)
epochs = 10

for _ in range(epochs):
    start = 0
    end = period_range
    funds = 1000.0
    orders = []
    error = 0.0
    print('training...', end=' ', flush=True)
    while run and end < candle_end:
        signal_in = prepare_input(candles, start, end)
        network.set_input(signal_in)
        network.feed_forward()
        network.back_propagate(signal_out[end])
        error += network.get_error(signal_out[end])
Exemple #6
0
 def __init__(self, ball, score):
     self.ball = ball
     self.score = score
     self.network = neural.Network(neural.layout.FeedForward(6, 2, *[15]*25))
Exemple #7
0
import math

pygame.init()
pygame.font.init()

WIDTH = 1200
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))

plr = player.Player(20, 20)

itemsize = 10
item = player.Item(random.randint(0, WIDTH - itemsize),
                   random.randint(0, HEIGHT - itemsize))

nn = neural.Network(4, 8, 4)
LR = 0.05

clock = pygame.time.Clock()
myfont = pygame.font.Font(None, 36)

accuracy = []

while True:  # main game loop

    ## set up the background & shit ##
    clock.tick(120)

    screen.fill((30, 30, 30))

    for event in pygame.event.get():
Exemple #8
0
			inputLayer = mini_batch.to_numpy()[:,3:].astype('float32')
			optimalOutput = mini_batch.to_numpy()[:,0:2].astype('float32')
			net.feedForward(inputLayer)
			#print(optimalOutput[0,0], net.network[-1].neurons[0,0])
			net.backPropagate(optimalOutput)
			error.append(np.mean(cost(net.network[-1].a, optimalOutput)))
	plt.plot(error)
	plt.show()

if __name__ == '__main__':

	# Gets dataset
	train_set, test_set = get_datasets('complete', .9)

	# Makes neural network with input layer, two hidden layers and one output layer
	net = neural.Network(learningRate = 0.008)
	net.addLayer(neural.Input(30))
	net.addLayer(neural.Dense(10, activation=RELU, diff_activation=RELU_diff))
	net.addLayer(neural.Dense(10, activation=RELU, diff_activation=RELU_diff))
	net.addLayer(neural.Output(2, costDiff=costDiff))
	net.finalise()

	# Trains and then tests
	train(train_set, net, 64)
	test(test_set, net)

	# Lets user test network with own words. Prints out score and guess
	run = True
	T = ['engelsk', 'norsk']
	while run:
		word = input("Ord: ")