Exemple #1
0
    def __init__(self, model, screen, track,
                 clr_outside_trk):  #model = [6,5,3,4]
        #game objects
        self.screen = screen
        self.track = track
        self.clr_outside_trk = clr_outside_trk

        #car setup
        self.xs = 600
        self.ys = 450
        self.xt = self.xs - 100
        self.yt = self.ys + 100
        self.dt = 1.0
        self.font = pygame.font.Font(None, 24)
        self.msg = ["STOP", "GEAR 1", "GEAR 2", "GEAR 3", "GEAR 4"]
        self.gears = []
        self.gear_lock = 24
        # for i in range(len(self.msg)):
        #     self.gears += [self.font.render(self.msg[i],1,(250,250,250))]
        self.speedo = []
        self.laps = []
        self.dist = []
        self.timer = 0
        self.direction = 0
        self.wobble = 15
        # for i in range(101):
        #     self.speedo += [self.font.render("SPEED "+str(i),1,(250,250,250))]
        #     self.laps += [self.font.render("LAP "+str(i),1,(250,250,250))]

        #Network
        self.score = 1
        self.network = neural_network.Network(model)
Exemple #2
0
def fnn(hidden_neurons, epochs, mini_batch_size, learning_rate,
        training_feedback, training_dataset_type: Training_Dataset):
    """Feedforward neural network using stochastic gradient descent."""

    # Loads traninig data
    training_data, validation_data, test_data = mnist_loader.load_data()

    # Select the training dataset
    if (training_dataset_type == Training_Dataset.Validation_Data):
        training_dataset = validation_data
    elif (training_dataset_type == Training_Dataset.Test_Data):
        training_dataset = test_data

    # Basic three-layers based neural network with 748 neurons on input layer,'hidden_neurons'
    # value as neurons on hidden layer, 10 neurons on output layer.
    net = neural_network.Network([784, hidden_neurons, 10])

    # Train the network with 'epochs' value epochs, 'mini_batch_size' digits as mini-batch size,
    # 'learning_rate' as learning rate and test feedback if 'training_feedback' is true.
    print_information("FNN - Quadratic Cost", hidden_neurons, epochs,
                      mini_batch_size, learning_rate)
    net.stochastic_gradient_descent(
        training_data,
        epochs,
        mini_batch_size,
        learning_rate,
        test_data=training_dataset if training_feedback else None)
Exemple #3
0
def main(filename):
    with open(filename) as json_file:
        data = json.load(json_file)
        for d in data:
            prefs[d] = data[d]

    neural_network.CONFIDENCE_THRESHOLD = prefs["confidence_threshold"]
    neural_network.CULMINATE_GENRES = prefs["genres"]
    neural_network.USE_MODEL = prefs["model_name"]
    neural_network.USE_CSV = prefs["data_csv"]
    neural_network.SPOTIFY_USERNAME = prefs["username"]
    neural_network.PLAYLIST_URIS = prefs["playlist_uris"]

    neural_network.in_depth_validate_predictions(neural_network.Network())
Exemple #4
0
def crossValidation(training_data):
    cv = cross_validation.KFold(len(training_data), n_folds=10, shuffle=True)
    for trainCV, testCV in cv:
        validation_training = map(training_data.__getitem__, trainCV)
        validation_test = map(training_data.__getitem__, testCV)
        y = [result[1] for result in validation_test]
        #zeros = sum(y)
        #ones = len(validation_test) - zeros
        #print "validation_test baseline: {0}/{1}".format(sum(y), len(y))

        net = neural_network.Network([104, 1])
        net.SGD(training_data,
                epochs=4,
                mini_batch_size=10,
                eta=0.1,
                test_data=validation_test)
Exemple #5
0
import data
import config
import random
import numpy as np
import neural_network

if __name__ == "__main__":
    #print("Start")
    data = data.Data()
    data.read_full(config.TRAIN_INPUT, config.TRAIN_LABELS, True)
    print("Train data read successfully")

    X, Y = data.get_data()

    network = neural_network.Network(config.NUM_TRAIN,
                                     config.IMAGE_SIZE * config.IMAGE_SIZE,
                                     config.CLASSES)
    network.train(X, Y)
    #   print("Complete model training")
    print("Accuracy Plot for Train")
    network.plot_accuracy('Train')
    print("Error Plot for Train")
    network.plot_cost('Train')
    print("Accuracy Plot for Validation")
    network.plot_accuracy('Validation')
    print("Error Plot for Validation")
    network.plot_cost('Validation')
    print("Plot T-SNE")
    network.plot_tsne()

    #   Test on Holdout Set
Exemple #6
0
__author__ = 'greg'
import loader
import neural_network

training_data, validation_data, test_data = loader.load_data_wrapper()
net = neural_network.Network([784, 30, 10])

net.SGD(training_data, 30, 10, 3.0, test_data=test_data)
Exemple #7
0
import neural_network as nnet
import numpy as np
import matplotlib.animation as mpa
import matplotlib.pyplot as plt


net = nnet.Network([784, 30, 20, 10], True)  # keep the already trained network


def get_activations():
    """Returns the results outputted by the network as a list of tuples in the form (x,y)
    x is an array of length 10, each index is a float, which is how confident the network is that the answer is that index
    y is the actual answer as an integer
    """
    return [(net.feedfoward(x), y) for (x, y) in nnet.test_data]


def show_performance():
    """
    Runs update_results
    """
    nnet.update_results()


def show_results(picture_data, result, itr):
    """
    Creates two subplots, one is the actual handwritten digit as an image, the second is a bar graph indexed from 0 to 10,
    representing the certainty of network in classifying each image.
    :param picture_data: list
        list in the form (x,y), x is an ndarray with shape (28,28) representing the handwritten digit in greyscale values,
        y is the value of the handwritten digit represented as an integer
Exemple #8
0
        cropped = frame[300:600, 400:900]
        gray_cropped = Image.fromarray(cropped).convert('L')
        row_avg = numpy.average(numpy.asarray(gray_cropped))
        avg = numpy.average(row_avg)
        print avg
        if avg > 165:
            count += 1
        if avg > 165 and count > 20:
            """
            thread this!
            """
            cv2.imwrite('capture.png', cropped)
            resized_images, segments, images = get_segments('capture.png')
            print segments
            segment_boxes = segments
            for i in xrange(len(images)):
                cv2.imwrite('segment-' + str(i) + '.png',
                            numpy.asarray(images[i]))
            last_frame_time = frame_time
            count = 0
            net = network.Network([784, 30, 13])
            net.load_parameters()
            for i in resized_images:
                print net.recognize(i)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
import neural_network
import data_retriever

training_data = data_retriever.get_data()

net = neural_network.Network([1, 1])

data_size = len(training_data)

net.SGD(training_data, 500, data_size, 0.02)

slope = net.weights[0][0][0]
intercept = net.biases[0][0][0]

print("Equation: y = {0}x {1} {2}".format(slope, "+" if intercept > 0 else "-",
                                          intercept))
Exemple #10
0
"""
test_network.py
~~~~~~~~~~
"""
import neural_network as network
import data_loader as dl
import numpy as np
from segmentation import get_segments

# training
training_data, validation_data, test_data = dl.load_data()
net = network.Network([784, 33, 13])
#net.train(training_data, test_data)

net.load_parameters()

print(net.evaluate(test_data))

# # segment big image
# segments = get_segments('test_img.png')

# results = []
# for seg in segments:
#     results.append(np.argmax(net.feedforward(seg)))

# print results
Exemple #11
0
    X, Y = data.read(config.MNIST_FILE)

    Y = np.where(
        Y == 7, 0,
        1)  ##Important to change Y as 0 where it is 7, Y as 1 where it is 9
    print("Train data read successfully")

    X_, Y_ = X[:-config.NUM_TEST], Y[:-config.NUM_TEST]
    X_test, Y_test = X[config.NUM_TRAIN +
                       config.NUM_VAL:], Y[config.NUM_TRAIN + config.NUM_VAL:]

    config.CLASS_LABELS = np.unique(Y_)
    config.CLASSES = len(config.CLASS_LABELS)

    network = neural_network.Network(config.NUM_TRAIN,
                                     config.IMAGE_SIZE * config.IMAGE_SIZE,
                                     len(config.CLASS_LABELS))

    network.train(X_, Y_)

    print("Accuracy Plot for Train")
    network.plot_accuracy('Train')
    print("Error Plot for Train")
    network.plot_cost('Train')
    print("Accuracy Plot for Validation")
    network.plot_accuracy('Validation')
    print("Error Plot for Validation")
    network.plot_cost('Validation')
    print("Plot T-SNE")
    utils.plot_tsne()