def main():

    (train_pictures, train_labels), (test_pictures,
                                     test_labels) = mnist.load_data()

    # (0-9)
    class_num = 10
    j = 1
    maxValue = 255
    fl = 'float32'

    for index in range(len(test_pictures)):
        cropped = srediSliku(test_pictures[index])
        test_pictures[index] = cropped

    for index in range(len(train_pictures)):
        cropped = srediSliku(train_pictures[index])
        train_pictures[index] = cropped

    row, col = train_pictures.shape[j:]

    train_data = train_pictures.reshape(train_pictures.shape[0], row, col, j)
    test_data = test_pictures.reshape(test_pictures.shape[0], row, col, j)
    shape = (row, col, j)

    train_data = train_data.astype(fl)
    test_data = test_data.astype(fl)

    # Scale the data to lie between 0 to 1
    train_data /= maxValue
    test_data /= maxValue

    # konverzija iz tipa int u categorical
    train_lab_categorical = to_categorical(train_labels)
    test_lab_categorical = to_categorical(test_labels)

    model = neural_network_model(shape, class_num)

    model.compile(optimizer='rmsprop',
                  loss='categorical_crossentropy',
                  metrics=['accuracy'])

    model.summary()

    #istorija
    hist = model.fit(train_data,
                     train_lab_categorical,
                     batch_size=256,
                     epochs=30,
                     verbose=1,
                     validation_data=(test_data, test_lab_categorical))
    loss, accuracy = model.evaluate(test_data, test_lab_categorical,
                                    verbose=0)  # racunamo gubitke i tacnost

    model.save_weights('neuralModel.h5')

    print(accuracy)
Beispiel #2
0
def train_model(training_data, model=False):
    # get training data from numpy array training_data
    X = np.array([i[0]
                  for i in training_data]).reshape(-1,
                                                   len(training_data[0][0]), 1)
    y = [i[1] for i in training_data]

    # if there isn't a pretrained model, make a new one
    if not model:
        model = neural_network_model(input_size=len(X[0]))

    # fit on training data
    model.fit({'input': X}, {'targets': y},
              n_epoch=5,
              snapshot_step=500,
              show_metric=True,
              run_id='2048_learning')
    return model
Beispiel #3
0
def predict(heatmap_type='jet'):

    # creates model of neural network
    prediction = neural_network_model(x, keep_prob)
    cross_entropy = tf.reduce_mean(
        tf.nn.sigmoid_cross_entropy_with_logits(logits=prediction, labels=y))

    images_for_prediction = np.array(
        load_data(args.images, (64, 64), first=5000))
    images_original = sorted(listdir_fullpath(args.images))[5000:]
    original_maps = np.array(load_data(args.maps, (64, 64), first=5000))
    saver = tf.train.Saver()

    with tf.Session() as sess:
        saver.restore(sess, args.model)  # restores saved model

        predicted_heatmaps = make_prediction(prediction, {
            x: images_for_prediction,
            keep_prob: 1.0
        })

        binary_maps = np.array(
            get_binary_fixation_maps(args.binary_maps, size=64, first=5000))

        count_metrics(predicted_heatmaps, original_maps, binary_maps)

        i = 0
        for map, img in zip(predicted_heatmaps, images_original):
            i += 1
            #print ("working on: " + str(img.rsplit('/', 1)[1]))
            # saving predicted heatmaps on image
            visualize_heatmap(map, img, args.save_to, heatmap_type)

            i += 1
            p = map
            print(str(i) + ". saving " + str(img.rsplit('/', 1)[1]))
            plt.imshow(p, cmap='jet')
            toimage(p).save("predicted_maps/" + str(img.rsplit('/', 1)[1]))
            plt.savefig("predicted_maps/plot_" + str(img.rsplit('/', 1)[1]))
            if i == 50:
                break
def main():

    global jezgro
    name = 'video-' + str(sys.argv[1]) + '.avi'
    video = cv2.VideoCapture(name)
    #video = cv2.VideoCapture('video-0.avi')
    ret, frame = video.read()

    shape = (28, 28, 1)
    class_number = 10

    klasifikator = neural_network_model(shape , class_number)
    klasifikator.load_weights(''
                              'neuralModel.h5')
    crvena = [6, 19, 216]
    zelena = (0, 255, 0)
    plava = (255, 153, 0)

    frameNum = 0
    allNum = [] # svi brojevi koji su bili na sceni
    sum = 0
    presao = True
    nijePresao = False

    kernel = jezgro
    linija = detektujLiniju(cv2.morphologyEx(frame, cv2.MORPH_OPEN, kernel=kernel))

    while ret:
        ret, frame = video.read()

        if not ret:
            break

        minTacka = linija[0]
        maxTacka = linija[1]

        konture = contoursOfNumbers(frame)

        for kontura in konture:

            cx, cy = centerOfPoints(kontura)

            element = {'point': (cx, cy), 'brFrame': frameNum, 'history': []}

            founded = detectNumbers(allNum, element)

            if len(founded) == 0:
                element['value'] = recognizeNumber(frame, kontura, klasifikator)
                element['presaoLiniju'] = nijePresao
                allNum.append(element)

            elif len(founded) == 1:
                i = founded[0]
                histo = {'brFrame': frameNum, 'point': element['point']}

                allNum[i]['history'].append(histo)

                allNum[i]['brFrame'] = frameNum

                allNum[i]['point'] = element['point']

            #ispitujemo da li je linija predjena
        for element in allNum:

            subb = frameNum - element['brFrame']
            rast = 3

            if (subb > rast):
                continue
            if not element['presaoLiniju']:

                distanca, _, r = vector.pnt2line(element['point'], minTacka, maxTacka)

                if r == 1 and distanca < 11.0:
                    #saberi brojeve
                    brojevi = element['value']
                    sum += int(brojevi)
                    element['presaoLiniju'] = presao


            cv2.circle(frame, element['point'], 18,crvena, 2)

            cv2.putText(frame, str(element['value']), (element['point'][0] + 12, element['point'][1] + 12),
                        cv2.FONT_HERSHEY_SIMPLEX, 1,zelena, 3)


            #Ispis teksta na ekranu
            #===============================================================================
            cv2.putText(frame,"Stefan Milovic RA164/2014", (15, 13), cv2.FONT_HERSHEY_SIMPLEX,
                        0.45, plava, 1)

            text = 'Sum: '
            cv2.putText(frame, text + str(sum), (15, 28), cv2.FONT_HERSHEY_SIMPLEX,
                        0.45,plava, 1)

            text1 = 'Number of curent frame: '
            cv2.putText(frame, text1 + str(frameNum), (15, 42), cv2.FONT_HERSHEY_SIMPLEX,
                        0.45,plava, 1)


            for history in element['history']:
                sub = frameNum - history['brFrame']
                dis = 70
                if (sub < dis):
                    cv2.circle(frame, history['point'], 1, (200, 200, 200), 1)

        cv2.imshow('Frame', frame)

        if cv2.waitKey(1) == 13:
            break
        counter = 1
        frameNum += counter

    cv2.destroyAllWindows()
    video.release()

    print ("Ukupan broj frejmova:", (frameNum))
    print ("Ukupan zbir  brojeva:", str(sum))

    f = open('out.txt', 'a')
    f.write('\n' + name + '\t' + str(sum))
    f.close()
Beispiel #5
0
import random
import numpy as np
import tflearn
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.estimator import regression
from statistics import mean, median
from collections import Counter
from game_2048 import Game, moves
from nn_model import neural_network_model

model = neural_network_model(16)
model.load('models/trained_nn.model')

scores = []
choices = []

game = Game()
goal_steps = 20000  # max number of steps
num_tests = 1000  # number of tests to amke


def test_run():
    random_moves = 0  # counter for number of times the model predicated an impossible move

    for each_game in range(num_tests):
        score = 0
        prev_obs = []
        game.reset()
        for _ in range(goal_steps):

            choice = None