tanmay
tanmay

Reputation: 225

How to retrieve dictionary key-value pair on the basis of array returned by a function in python 3

I am new to coding to python and one of the function returns a numpy.ndarray with six values like this

[1 0 1 0 1 1]

These are actually predictions of a multiclass classification model and will have a value 1 in case of a match else 0.

I wish to give these six predictions some meaning for which I created a dictionary as below:

toxics = {1:'Toxic', 2:'Severely Toxic', 3:'Obscene', 4:'Threat', 5:'Insult', 6:'Identity Hate'}

How can I map/link my individual prediction with the dictionary and display/print some message for the user. For example in the above data something like:

"The text is Toxic, Obscene, Insult, Identity Hate" as I have a prediction of '1' at 0,2,4,5 position in the array.

Thanks in advance.

Upvotes: 0

Views: 413

Answers (3)

Chris Doyle
Chris Doyle

Reputation: 12027

You dont need a dict, you can simply use zip to tie your predictions to your toxics. you can then just use a list comprehension to get those which are 1. You can use np.where to get the index values.

from numpy import array, where

preds = array([1, 0, 1, 0, 1, 1])
toxics = ["Toxic", "Severely Toxic", "Obscene", "Threat", "Inuslt", "Identity Hate"]
results = [toxic for pred, toxic in zip(preds, toxics) if pred == 1]
indexs = where(preds == 1)

print("'The text is", ", ".join(results) + "' as i have a prediction of '1' at",  ",".join([str(i) for i in indexs[0]]))

OUTPUT

'The text is Toxic, Obscene, Inuslt, Identity Hate' as i have a prediction of '1' at 0,2,4,5

Upvotes: 1

Code Pope
Code Pope

Reputation: 5449

Here a sample code, how you can do it:

import numpy as np
results =np.array([1,0,1,0, 1, 1])
toxics = {1:'Toxic', 2:'Severely Toxic', 3:'Obscene', 4:'Threat', 5:'Insult', 6:'Identity Hate'}
strings =[toxics[k] for k in (np.argwhere(results==1)+1).reshape(-1) if k in toxics]
'The text is ' + ', '.join(strings)+' as I have a prediction of 1 at ' + ', '.join(np.char.mod('%d',(np.argwhere(results==1)).reshape(-1)))

Output:

'The text is Toxic, Obscene, Insult, Identity Hate as I have a prediction of 1 at 0, 2, 4, 5'

Upvotes: 1

HNMN3
HNMN3

Reputation: 542

Here is the simple comprehension to achieve the above results:

arr = [1, 0, 1, 0, 1, 1]
toxic_str = ",".join([toxics[i] for i, val in enumerate(arr, 1) if val == 1])
print("This text is", toxic_str)

enumerate(arr, 1) will return a list of tuples having index(starting from 1) and value.

Hope this helps!!

Upvotes: 2

Related Questions