Esempio n. 1
0
def check_keys(my_data):
    # test for various keyboard inputs
    (event, background, draw_color, line_width, keep_going, screen, mat) = my_data

    if event.key == pygame.K_q:
        keep_going = False

    elif event.key == pygame.K_c:
        background.fill((255, 255, 255))
        draw_pixelated(np.zeros((28, 28)), screen)

    # s - for saving a digit and pattern
    elif event.key == pygame.K_s:
        answer = int(ask(screen, ""))

        f_m = matrix_manipulate.focus_mat(mat)

        shrinking_model.learn_pattern(f_m, answer, "one_zero_shrinking")
        extended_model.learn_pattern(f_m, answer, "one_zero_extended")
        multiplication_model.learn_pattern(f_m, answer, "one_zero_multiplication")

        """shrinking_model.learn_pattern(f_m, answer, "shrinking_model")
        extended_model.learn_pattern(f_m, answer, "extended_model")
        multiplication_model.learn_pattern(f_m, answer, "multiplication_model")"""

    # t - for testing some real time hand write digit
    elif event.key == pygame.K_t:
        model_tester.test_model(my_data, 'one_zero_shrinking')
        model_tester.test_model(my_data, 'one_zero_extended')
        model_tester.test_model(my_data, 'one_zero_multiplication')

        """model_tester.test_model(my_data, 'multiplication_model')
        model_tester.test_model(my_data, "shrinking_model")
        model_tester.test_model(my_data, "extended_model")"""

    background.fill((255, 255, 255))
    draw_pixelated(np.zeros((28, 28)), screen)

    my_data = (event, background, draw_color, line_width, keep_going)
    return my_data
Esempio n. 2
0
def main():
    file_name = {
        'images':
        'C:\\Users\\asafm\\PycharmProjects\\Final-Project\\samples\\train-images.idx3-ubyte',
        'labels':
        'C:\\Users\\asafm\\PycharmProjects\\Final-Project\\samples\\train-labels.idx1-ubyte'
    }
    labels_array = np.array([])

    data_types = {
        0x08: ('ubyte', 'B', 1),
        0x09: ('byte', 'b', 1),
        0x0B: ('>i2', 'h', 2),
        0x0C: ('>i4', 'i', 4),
        0x0D: ('>f4', 'f', 4),
        0x0E: ('>f8', 'd', 8)
    }

    for name in file_name.keys():
        if name == 'images':
            images_file = open(file_name[name], 'rb')
        if name == 'labels':
            labels_file = open(file_name[name], 'rb')

    images_file.seek(0)
    magic = st.unpack('>4B', images_file.read(4))
    if (magic[0] and magic[1]) or (magic[2] not in data_types):
        raise ValueError("File Format not correct")

    nDim = magic[3]
    print("Data is ", nDim, "-D")

    # offset = 0004 for number of images
    # offset = 0008 for number of rows
    # offset = 0012 for number of columns
    # 32-bit integer (32 bits = 4 bytes)
    images_file.seek(4)
    nImg = st.unpack('>I', images_file.read(4))[0]  # num of images/labels
    nR = st.unpack('>I', images_file.read(4))[0]  # num of rows
    nC = st.unpack('>I', images_file.read(4))[0]  # num of columns
    nBytes = nImg * nR * nC
    labels_file.seek(
        8)  # Since no. of items = no. of images and is already read
    print("no. of images :: ", nImg)
    print("no. of rows :: ", nR)
    print("no. of columns :: ", nC)

    # Read all data bytes at once and then reshape
    images_array = 255 - np.asarray(
        st.unpack('>' + 'B' * nBytes, images_file.read(nBytes))).reshape(
            (nImg, nR, nC))
    labels_array = np.asarray(
        st.unpack('>' + 'B' * nImg, labels_file.read(nImg))).reshape((nImg, 1))

    for i in tqdm(range(60000)):
        lable = labels_array[i][0]
        mat = range(784)
        mat = np.reshape(mat, (28, 28))
        for j in range(28):
            for h in range(28):
                if images_array[i][j][h] == 255:
                    mat[j][h] = 0
                else:
                    mat[j][h] = 1
        m = matrix_manipulate.focus_mat(mat)
        #sum_model.learn_pattern(m, lable, "sum_model")
        shrinking_model.learn_pattern(m, lable, "shrinking_model")
        #extended_model.learn_pattern(m, lable, "extended_model")
        #multiplication_model.learn_pattern(m, lable, "multiplication_model")

    print('Finish to load MNIST dataset')
Esempio n. 3
0
def main():
    for arg in sys.argv[1:]:
        file_name = {
            'images':
            'C:\\Users\\asafm\\PycharmProjects\\Final-Project\\samples\\t10k-images.idx3-ubyte',
            'labels':
            'C:\\Users\\asafm\\PycharmProjects\\Final-Project\\samples\\t10k-labels.idx1-ubyte'
        }
        labels_array = np.array([])

        data_types = {
            0x08: ('ubyte', 'B', 1),
            0x09: ('byte', 'b', 1),
            0x0B: ('>i2', 'h', 2),
            0x0C: ('>i4', 'i', 4),
            0x0D: ('>f4', 'f', 4),
            0x0E: ('>f8', 'd', 8)
        }

        for name in file_name.keys():
            if name == 'images':
                images_file = open(file_name[name], 'rb')
            if name == 'labels':
                labels_file = open(file_name[name], 'rb')

        images_file.seek(0)
        magic = st.unpack('>4B', images_file.read(4))
        if (magic[0] and magic[1]) or (magic[2] not in data_types):
            raise ValueError("File Format not correct")

        nDim = magic[3]
        print("Data is ", nDim, "-D")

        # offset = 0004 for number of images
        # offset = 0008 for number of rows
        # offset = 0012 for number of columns
        # 32-bit integer (32 bits = 4 bytes)
        images_file.seek(4)
        nImg = st.unpack('>I', images_file.read(4))[0]  # num of images/labels
        nR = st.unpack('>I', images_file.read(4))[0]  # num of rows
        nC = st.unpack('>I', images_file.read(4))[0]  # num of columns
        nBytes = nImg * nR * nC
        labels_file.seek(
            8)  # Since no. of items = no. of images and is already read
        print("no. of images :: ", nImg)
        print("no. of rows :: ", nR)
        print("no. of columns :: ", nC)

        # Read all data bytes at once and then reshape
        images_array = 255 - np.asarray(
            st.unpack('>' + 'B' * nBytes, images_file.read(nBytes))).reshape(
                (nImg, nR, nC))
        labels_array = np.asarray(
            st.unpack('>' + 'B' * nImg, labels_file.read(nImg))).reshape(
                (nImg, 1))

        sum = 0
        num_of_samples = 0
        for i in tqdm(range(10000)):
            lable = labels_array[i][0]
            if lable == 1 or lable == 0:
                num_of_samples = num_of_samples + 1
                mat = range(784)
                mat = np.reshape(mat, (28, 28))
                for j in range(28):
                    for h in range(28):
                        if images_array[i][j][h] == 255:
                            mat[j][h] = 0
                        else:
                            mat[j][h] = 1
                m = matrix_manipulate.focus_mat(mat)
                result = test_machine(m, arg)
                if result == lable:
                    sum += 1

        print(
            '===============================================================')
        print(
            'Finish to Test the machine with MNIST dataset on {}'.format(arg))
        print('Num of samples = ', num_of_samples)
        print('num of correct answers = ', sum)
        print('Accuracy of the machine is: ', (sum / num_of_samples) * 100,
              '%')
        print(
            '===============================================================')
Esempio n. 4
0
def test_model(my_data, model_name):
    (event, background, draw_color, line_width, keep_going, screen,
     mat) = my_data
    f_m = focus_mat(mat)
    if 'shrinking' in model_name:
        pattern = shrinking_model.get_pattern(f_m)
    elif 'extended' in model_name:
        pattern = extended_model.get_pattern(f_m)
    elif 'multiplication' in model_name:
        pattern = multiplication_model.get_pattern(f_m)
    elif 'sum' in model_name:
        pattern = sum_model.get_pattern(f_m)

    try:
        cnx = connector.connect(user='******',
                                password='******',
                                database='hand_write_recognition')
        cursor = cnx.cursor()

        query = ("SELECT digit FROM {} WHERE pattern = {}".format(
            model_name, pattern))

        cursor.execute(query)
        digits = []
        for digit in cursor:
            digits.append(digit)

        guess1mount = guess2mount = 0
        try:
            print('*** TEST FOR {} ***'.format(model_name))
            guess1is = Counter(digits).most_common(2).pop(0)[0][0]
            guess1mount = Counter(digits).most_common(2).pop(0)[1]
            print('Guess 1 is :', guess1is)
        except IndexError:
            print('I could not guess a single number as a first guess.')

        try:
            guess2is = Counter(digits).most_common(2).pop(1)[0][0]
            guess2mount = Counter(digits).most_common(2).pop(1)[1]
            print('Guess 2 is :', guess2is)
        except IndexError:
            print('I could not guess a single number as a second guess.')

        sum = guess1mount + guess2mount
        try:
            print('Accuracy of :', guess1is, ': ', (guess1mount / sum) * 100,
                  '%')
            print('Accuracy of :', guess2is, ': ', (guess2mount / sum) * 100,
                  '%')
        except UnboundLocalError:
            print('I could not calculate the accuracy')

        cursor.close()

    except connector.Error as err:
        if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
            print("Something is wrong with your user name or password")
        elif err.errno == errorcode.ER_BAD_DB_ERROR:
            print("Database does not exist")
        else:
            print(err)

    else:
        cnx.close()