0

I used GPT-3 to generate a Neural Network to use in a simple "cell" simulator.

When I run the script, I get the following error :

*hidden_errors = np.dot(output_errors, self.weights_hidden_to_output.T)
  File "<__array_function__ internals>", line 5, in dot
ValueError: shapes (1,4) and (2,1) not aligned: 4 (dim 1) != 2 (dim 0)*

I know this is because the matrices are not correctly shaped and I tried transposing it but without success. I also tried modifying the inputs list without any success.

import random
import pygame
import numpy as np

class Hero:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.score = 0

    def move_towards_food(self, food):
        if self.x < food.x:
            self.x += 1
        elif self.x > food.x:
            self.x -= 1
        if self.y < food.y:
            self.y += 1
        elif self.y > food.y:
            self.y -= 1

    def get_score(self):
        return self.score
    def respawn(self):
        self.x = random.randint(20,980)
        self.y = random.randint(20,980)


class Villain:
    def __init__(self):
        self.x = random.randint(0,1000)
        self.y = random.randint(0,1000)

    def move_towards_hero(self, hero):
        if self.x < hero.x:
            self.x += 1
        elif self.x > hero.x:
            self.x -= 1
        if self.y < hero.y:
            self.y += 1
        elif self.y > hero.y:
            self.y -= 1


class Food:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class NeuralNetwork:
    def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate):
        self.input_nodes = input_nodes
        self.hidden_nodes = hidden_nodes
        self.output_nodes = output_nodes
        self.learning_rate = learning_rate
        self.weights_input_to_hidden = np.random.normal(0.0, self.input_nodes ** -0.5,
                                                        (self.input_nodes, self.hidden_nodes))
        self.weights_hidden_to_output = np.random.normal(0.0, self.hidden_nodes ** -0.5,
                                                         (self.hidden_nodes, self.output_nodes))
        self.activation_function = lambda x: 1 / (1 + np.exp(-x))

    def train(self, inputs_list, targets_list):
        inputs = np.array(inputs_list, ndmin=2).T
        targets = np.array(targets_list, ndmin=2).T
        hidden_inputs = np.dot(self.weights_input_to_hidden, inputs)
        hidden_outputs = self.activation_function(hidden_inputs)
        final_inputs = np.dot(self.weights_hidden_to_output, hidden_outputs)
        final_outputs = final_inputs
        output_errors = targets - final_outputs
        hidden_errors = np.dot(self.weights_hidden_to_output.T, output_errors)
        self.weights_hidden_to_output += self.learning_rate * np.dot(
            output_errors * final_outputs * (1.0 - final_outputs), hidden_outputs.T)
        self.weights_input_to_hidden += self.learning_rate * np.dot(
            hidden_errors * hidden_outputs * (1.0 - hidden_outputs), inputs.T)

    def run(self, inputs_list):
        inputs = np.array(inputs_list, ndmin=2).T
        hidden_inputs = np.dot(self.weights_input_to_hidden, inputs)
        hidden_outputs = self.activation_function(hidden_inputs)
        final_inputs = np.dot(self.weights_hidden_to_output, hidden_outputs)
        final_outputs = final_inputs
        return final_outputs

hero = Hero(500, 500)
villain = Villain()
food = Food(random.randint(0, 1000), random.randint(0, 1000))

nn = NeuralNetwork(4, 4, 4, 0.5)

inputs = [[1, 0, 1, 0], [0, 1, 0, 1], [1, 1, 1, 0], [0, 0, 0, 1]]
targets = [[1], [1], [0], [0]]

nn.train(inputs, targets)
hero.nn = nn

pygame.init()
size = [1000, 1000]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Hero Game")

black = [0, 0, 0]
white = [255, 255, 255]
red = [255, 0, 0]
green = [0, 255, 0]

font = pygame.font.SysFont('Calibri', 25, True, False)

done = False
clock = pygame.time.Clock()

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
    screen.fill(white)
    text = font.render("Hero: " + str(hero.x) + ", " + str(hero.y), True, black)
    screen.blit(text, [50, 50])
    text = font.render("Villain: " + str(villain.x) + ", " + str(villain.y), True, black)
    screen.blit(text, [50, 100])
    text = font.render("Food: " + str(food.x) + ", " + str(food.y), True, black)
    screen.blit(text, [50, 150])
    text = font.render("Score: " + str(hero.get_score()), True, black)
    screen.blit(text, [50, 200])
    pygame.draw.rect(screen, red, [hero.x, hero.y, 5, 5])
    pygame.draw.rect(screen, black, [villain.x, villain.y, 5, 5])
    pygame.draw.rect(screen, green, [food.x, food.y, 5, 5])

    # villain chase
    if villain.x < hero.x:
        villain.x += 1
    if villain.x > hero.x:
        villain.x -= 1
    if villain.y < hero.y:
        villain.y += 1
    if villain.y > hero.y:
        villain.y -= 1

    # -1 and respawn for villain touch
    if villain.x == hero.x and villain.y == hero.y:
        hero.score -= 1
        hero.respawn()

    inputs = [[hero.x / 1000, hero.y / 1000, food.x / 1000, food.y / 1000]]
    output = nn.run(inputs)
    if output[0][0] > 0.5:
        hero.move_towards_food(food)
    if hero.x == food.x and hero.y == food.y:
        hero.score += 1
        food = Food(random.randint(0, 1000), random.randint(0, 1000))

    pygame.display.flip()
    pygame.display.update()
    clock.tick(60)

pygame.quit()
desertnaut
  • 57,590
  • 26
  • 140
  • 166
  • Have you tried printing the shapes of the matrices, i.e. `output_errors` and `self.weights_hidden_to_output`? – Jake Tae Mar 28 '22 at 03:27
  • After printing them, I now understand why they are shaped differently. I think I must change the argument of the following line : self.weights_hidden_to_output = np.random.normal(0.0, self.hidden_nodes ** -0.5, (self.hidden_nodes, self.output_nodes)) – Jacques L'Éventreur Mar 28 '22 at 11:26

0 Answers0