NikSp
NikSp

Reputation: 1539

replace index by the element name with keeping the name's order and not the order of the index

I have a list of genres

genres_list=['Action', 'Adventure', 'Animation', 'Children', 'Comedy']

And I have neural network that predicts the sequence of the genres for this movie. From the predictions I keep the index of the top 3 genres. So for example if a movie is ["Animation", "Comedy", "Children"] then I will have a prediction like [2 4 3]. And then I replace the indexes [2 4 3] by their name from the initial list.

My current output is ["Animation", "Children", "Comedy"] because the First Index is First Replaced. But since it's important to keep the correct sequence (order) of the genres I want my final output to be like ["Animation", "Comedy", "Children"] -> the correct index prediction

my function (that produces the undesired results)

def predict_genre_tags(model, genres_list):
        
    test_sequence_actors = X_test_seq_actors[0:0+1]
    
    test_sequence_plot = X_test_seq_plot[0:0+1]
    
    test_sequence_features = X_test_seq_features[0:0+1]
    
    test_sequence_reviews = X_test_seq_reviews[0:0+1]
    
    text_prediction = model.predict([test_sequence_actors, test_sequence_plot, test_sequence_features, test_sequence_reviews])
    
    [float(i) for i in text_prediction[0]]
    
    tag_probabilities = text_prediction[0][np.argsort(text_prediction[0])[-3:]]
    
    indexes = np.argsort(text_prediction[0])[::-1][:3] #keep the genres with the top 3 probabilities and their index.
    
    print(indexes) # indexes= [2 4 3] based on my description
    
    predicted_tags = []
    
    for i, tag in enumerate(genres_list): #here is my problem...because the first inside the loop is the first replaced
        if i in indexes:
            predicted_tags.append(genres_list[i])
    
    return predicted_tags
df_predictions = pd.DataFrame({'Movie Title':pd.Series("Toy Story", dtype='str'),
                               'Predicted Genre tags (top 3)':pd.Series([predict_genre_tags(model, genres_list)], dtype='str') #which yields ["Animation", "Children", "Comedy"] genres in incorrect order,
                               'Real Genre tags':pd.Series(["Animation", "Comedy", "Children"], dtype='str')})

Upvotes: 0

Views: 30

Answers (1)

prayingMantis
prayingMantis

Reputation: 159

You can simply do this predicted_tags = [genres_list[i] for i in indexes].

Upvotes: 1

Related Questions