def plot_pokemon(id=random.randint(1, 700)):
    ''' 
    plots images of a pokemon given id 
    across all generations of games and data available
    '''
    path = "data/main-sprites/"
    game_folders = sorted(
        [x for x in os.listdir(path) if not x.startswith('.')])
    image = "{n}.png".format(n=id)
    plt.figure(figsize=(20, 4))

    # plot pokemon from all folders
    counter = 1
    for folder in game_folders:
        try:
            img = mpimg.imread(os.path.join(path, folder, image))
            plt.subplot(2, 8, counter)
            plt.imshow(img)
            plt.title(str(folder))
            counter += 1
        except FileNotFoundError:
            pass

    # can't forget the icon
    img = mpimg.imread(os.path.join("data/icons/", image))
    plt.subplot(2, 8, counter)
    plt.imshow(img)
    plt.title("icon")

    # we'll tell you the name as well
    plt.suptitle("Pokemon #" + str(id) + " " + get_pokemon(str(id)).name)
    plt.show()
Beispiel #2
0
def predict_single(img, classifier, test_set):
    ''' predicts the type of the pokemon given by "img" '''
    test_image = load_image(img)
    result1 = classifier.predict_classes(test_image)
    predicted_type = [
        type for type, index in test_set.class_indices.items()
        if index == result1[0]
    ][0]
    pokemon = get_pokemon(img)
    return predicted_type
Beispiel #3
0
def run(evaluate=True, predict=True):

    classifier, classifier2 = load_models()

    # tests
    test = 'type1_sorted/test'
    path = test + '/' + random.choice(
        [x for x in os.listdir(test) if os.path.isdir(os.path.join(test, x))])
    imagepath = path + '/' + random.choice(os.listdir(path))

    # load test sets
    test_datagen = ImageDataGenerator(rescale=1. / 255)
    test_set = test_datagen.flow_from_directory(test,
                                                target_size=(32, 32),
                                                batch_size=32,
                                                class_mode='categorical')
    test_set2 = test_datagen.flow_from_directory('type2_sorted/test',
                                                 target_size=(32, 32),
                                                 batch_size=32,
                                                 class_mode='categorical')

    if predict:
        test_image = load_image(imagepath)
        result1 = classifier.predict_classes(test_image)
        result2 = classifier2.predict_classes(test_image)

        predicted_type = [
            type for type, index in test_set.class_indices.items()
            if index == result1[0]
        ][0]

        predicted_type2 = [
            type for type, index in test_set2.class_indices.items()
            if index == result2[0]
        ][0]

        pokemon = get_pokemon(imagepath)
        second = "" if pokemon.type2 == 'None' else " and type " + pokemon.type2
        pred_sec = "" if predicted_type2 == 'None' else " and " + predicted_type2
        print("The Pokemon " + pokemon.name + " has type " + pokemon.type1 +
              second)
        print("The predicted type is " + predicted_type + second)

    if evaluate:
        print("Primary Type:")
        accuracy = classifier.evaluate_generator(test_set)
        print("Loss: ", accuracy[0])
        print("Accuracy: ", accuracy[1])

        print("Secondary:")
        accuracy2 = classifier2.evaluate_generator(test_set2)
        print("Loss: ", accuracy2[0])
        print("Accuracy: ", accuracy2[1])
Beispiel #4
0
def labels(window, type_labels, pokemon_id, player_counter, AI_counter,
           prediction, classifier, test_set, name_txt):
    typing = types('data/Pokemon-2.csv')
    path = "data/type_labels/"
    type = get_pokemon(pokemon_id).type1
    AI_answer = (type == prediction)

    type_labels[0] = (path + type + '.png', True)

    for i in range(1, 4):
        name = path + random.choice(os.listdir(path))
        temp = [a for b in type_labels for a in b]
        while str(name).endswith('.DS_Store') or name in temp:
            name = path + random.choice(os.listdir(path))
        type_labels[i] = (name, False)

    for i in range(4):
        pilImage = Image.open(type_labels[i][0])
        image = ImageTk.PhotoImage(pilImage)
        type_labels[i] = (image, type_labels[i][1])

    random.shuffle(type_labels)

    btn1 = Button(window,
                  image=type_labels[0][0],
                  command=lambda: clicked(window, type_labels, type_labels[0][
                      1], player_counter, AI_counter, AI_answer, classifier,
                                          test_set, name_txt))
    btn2 = Button(window,
                  image=type_labels[1][0],
                  command=lambda: clicked(window, type_labels, type_labels[1][
                      1], player_counter, AI_counter, AI_answer, classifier,
                                          test_set, name_txt))
    btn3 = Button(window,
                  image=type_labels[2][0],
                  command=lambda: clicked(window, type_labels, type_labels[2][
                      1], player_counter, AI_counter, AI_answer, classifier,
                                          test_set, name_txt))
    btn4 = Button(window,
                  image=type_labels[3][0],
                  command=lambda: clicked(window, type_labels, type_labels[3][
                      1], player_counter, AI_counter, AI_answer, classifier,
                                          test_set, name_txt))

    btn1.place(x=100, y=200, anchor="center")
    btn2.place(x=100, y=250, anchor="center")
    btn3.place(x=200, y=200, anchor="center")
    btn4.place(x=200, y=250, anchor="center")
Beispiel #5
0
def next_pokemon(window, classifier, test_set, name_txt):
    path = "data/main-sprites/"

    game_vers = random.choice(os.listdir(path))
    while str(game_vers).endswith('.DS_Store'):
        game_vers = random.choice(os.listdir(path))
    img = random.choice(os.listdir(path + game_vers))
    while not str(img).endswith('png'):
        img = random.choice(os.listdir(path + game_vers))
    file_name = path + game_vers + '/' + img

    pilImage = Image.open(file_name)
    pilImage = pilImage.resize((100, 100), Image.ANTIALIAS)
    image = ImageTk.PhotoImage(pilImage)
    p = Label(window, image=image)
    p.photo = image
    p.place(x=150, y=130, anchor="center")
    name_txt.set(get_pokemon(img).name)

    prediction = predict_single(file_name, classifier, test_set)

    return img, prediction
Beispiel #6
0
def plot_game(game, pokemons = random.sample(range(1, 152), 10)):
    ''' 
    plots list of pokemons in a given game or the icons folder
    '''
    path = "data/main-sprites/"
    full_path = os.path.join(path, game) if game is not "icons" else "data/icons"
    batch = len(pokemons)
    plt.figure(figsize = (20, 4))

    # plot the pokemon from pokemons
    counter = 1
    for id in pokemons:
        try:
            image = "{n}.png".format(n = id)
            img = mpimg.imread(os.path.join(full_path, image))
            plt.subplot(1, batch, counter)
            plt.imshow(img)
            plt.title(get_pokemon(str(id)).name)
            counter += 1
        except FileNotFoundError:
            pass
    plt.suptitle("Pokemons from " + str(game))
    plt.show()
Beispiel #7
0
def run(evaluate=True, predict=True):
    '''
    function to perform prediction using models
    evaluate determines whether to evaluate model through 
    the Keras evaluation function, computing precision/recall statistics
    predict will sample a random pokemon image to predict
    '''

    classifier, classifier2 = load_models()

    # tests
    test = 'type1_sorted/test'
    path = test + '/' + random.choice(
        [x for x in os.listdir(test) if os.path.isdir(os.path.join(test, x))])
    imagepath = path + '/' + random.choice(os.listdir(path))

    # load test sets
    test_datagen = ImageDataGenerator(rescale=1. / 255)
    test_set = test_datagen.flow_from_directory(test,
                                                target_size=(32, 32),
                                                class_mode='categorical')
    test_set2 = test_datagen.flow_from_directory('type2_sorted/test',
                                                 target_size=(32, 32),
                                                 batch_size=32,
                                                 class_mode='categorical')

    if predict:
        # predict random pokemon
        test_image = load_image(imagepath)
        result1 = classifier.predict_classes(test_image)
        result2 = classifier2.predict_classes(test_image)

        predicted_type = [
            type for type, index in test_set.class_indices.items()
            if index == result1[0]
        ][0]

        predicted_type2 = [
            type for type, index in test_set2.class_indices.items()
            if index == result2[0]
        ][0]

        pokemon = get_pokemon(imagepath)
        second = "" if pokemon.type2 == 'None' else " and type " + pokemon.type2
        pred_sec = "" if predicted_type2 == 'None' else " and " + predicted_type2
        print("The Pokemon " + pokemon.name + " has type " + pokemon.type1 +
              second)
        print("The predicted type is " + predicted_type + pred_sec)
        plot_type(imagepath,
                  predicted=True,
                  pred_types=[predicted_type, predicted_type2])

    if evaluate:
        # evaluates models
        print("Primary Type:")
        accuracy = classifier.evaluate_generator(test_set)

        v_t, v_p = stats(test_set.class_indices, classifier)
        report = classification_report(v_t,
                                       v_p,
                                       target_names=list(
                                           test_set.class_indices.keys()))
        print(report)
        print("Accuracy: ", accuracy_score(v_t, v_p))

        print("\n ------------------------------- \n")
        print("Evaluation Statistics")
        print("Loss: ", accuracy[0])
        print("Accuracy: ", accuracy[1])

        print("\n ------------------------------- \n")
        print("Secondary Type:")
        accuracy2 = classifier2.evaluate_generator(test_set2)

        v_t, v_p = stats(test_set2.class_indices, classifier2, primary=False)
        report = classification_report(v_t,
                                       v_p,
                                       target_names=list(
                                           test_set2.class_indices.keys()))
        print(report)
        print("Accuracy: ", accuracy_score(v_t, v_p))

        print("\n ------------------------------- \n")
        print("Evaluation Statistics")
        print("Loss: ", accuracy2[0])
        print("Accuracy: ", accuracy2[1])

    return classifier, test_set
Beispiel #8
0
def plot_type(imgpath = "", predicted = False, pred_types = []):
    ''' 
    plots the true type of the pokemon with its image 
    if predicted, then will plot the predicted types as well
    '''
    
    pkmn = get_pokemon(imgpath)
    dual_type = False if pkmn.type2 is "None" else True

    grid_rows = 3 if predicted else 2
    grid_cols = 2 if dual_type else 1
    figsize = (4, 4)        
    width_ratio = (1, 1) if dual_type else (1, )
    height_ratio = (12, 1, 1) if predicted else (12, 1)

    if dual_type:
        plt.figure(figsize = figsize)
        gs = gridspec.GridSpec(grid_rows, grid_cols, height_ratios = height_ratio, width_ratios = width_ratio)
        gs.update(wspace= 0.1, hspace= 0.5)
        ax0 = plt.subplot(gs[0, :])
        image = mpimg.imread(imgpath)
        img = ax0.imshow(image)
        plt.axis('off')
        
        ax1 = plt.subplot(gs[1, 0])
        typepath = "data/type_labels/{n}.png".format(n = pkmn.type1)
        typeicon = mpimg.imread(typepath)
        ax1.imshow(typeicon)
        plt.axis('off')
        
        ax1 = plt.subplot(gs[1, 1])
        type2path = "data/type_labels/{n}.png".format(n = pkmn.type2)
        type2icon = mpimg.imread(type2path)
        ax1.imshow(type2icon)
        plt.axis('off')
        
    else:
        plt.figure(figsize = figsize)
        gs = gridspec.GridSpec(grid_rows, grid_cols, height_ratios = height_ratio, width_ratios = width_ratio)
        gs.update(wspace= 0.25, hspace= 0.5)
        ax0 = plt.subplot(gs[0])
        image = mpimg.imread(imgpath)
        img = ax0.imshow(image)
        plt.axis('off')
    
        ax1 = plt.subplot(gs[1])
        typepath = "data/type_labels/{n}.png".format(n = pkmn.type1)
        typeicon = mpimg.imread(typepath)
        ax1.imshow(typeicon)
        plt.axis('off')

    if predicted:

        if dual_type:
            ax3 = plt.subplot(gs[2, 0])
            plt.text(-80, 12, "Predicted:")
            typepath = "data/type_labels/{n}.png".format(n = pred_types[0])
            typeicon = mpimg.imread(typepath)
            ax3.imshow(typeicon)
            plt.axis('off')

            ax4 = plt.subplot(gs[2, 1])
            try:
                typepath = "data/type_labels/{n}.png".format(n = pred_types[1])
                typeicon = mpimg.imread(typepath)
                ax4.imshow(typeicon)

            except FileNotFoundError:
                pass
            plt.axis('off')

        else:
            ax3 = plt.subplot(gs[2, :])
            plt.text(-80, 12, "Predicted:")
            typepath = "data/type_labels/{n}.png".format(n = pred_types[0])
            typeicon = mpimg.imread(typepath)
            ax3.imshow(typeicon)
            plt.axis('off')

    plt.suptitle(pkmn.name)
    plt.show()