简体   繁体   中英

Using an 'else' in list comprehension

I am using Python and I am predicting the attributes of clothing present in images of fashion models. The predictions are built up using the following code:

ATTRIBUTE RECOGNITION MODEL

#Importing necessary libraries
import torch
import torchvision.models as models
from torchvision import transfor
from torch.autograd import Variable
from PIL import Image
import torch.nn as nn
import numpy as np

#Defining the functions to load and use the model
def get_tensor(img):
    tfms = transforms.Compose([
    transforms.Resize((256, 256)),
    transforms.ToTensor()
    ])
    return tfms(Image.open(img)).unsqueeze(0)


def predict(img, label_lst, model):
    tnsr = get_tensor(img)
    op = model(tnsr)
    op_b = torch.round(op)
    op_b_np = torch.Tensor.cpu(op_b).detach().numpy()
    preds = np.where(op_b_np ==1)[1]
    sigs_op = torch.Tensor.cpu(torch.round((op)*100)).detach().numpy()[0]
    o_p = np.argsort(torch.Tensor.cpu(op).detach().numpy())[0][::-1]
    label = []
    for i in preds:
        label.append(label_lst[i])
    arg_s = {}
    for i in o_p:
        arg_s[label_lst[int(i)]] = sigs_op[int(i)]
    return label, list(arg_s.items())[:10]

#Load the model

labels = open(ATTRIBUTE_PATH, 'r').read().splitlines()

model = torch.load(ATTRIBUTE_MODEL_PATH, map_location=torch.device('cpu'))
model = model.eval()

#Use the model to iterate over the rows of our clothing dataframe and adding a column with the predictions
predictions=[]
for x in df_images["Media"]:
    p= predict(x, labels, model)
    predictions.append(p)
    
    
out = [[i for i, v in lst if v > -200 else i == i[0]] for _, lst in predictions]
df_images["Attributes"] = out
df_images.head()

The above is working fine for me. I am retrieving all the values of i in i,v where v > -200.

However, I want to add an else condition specifing, if there is no value for i in i, v where v > -200, return i[0] for i in i, v. (ie the i where v is the highest in i,v)

The reason I want to do this is because for some images now attribute predictions are being returned as they don't meet the thresholdof -200. Therefor, for I want to return the most likely attribute out of the list of identified possible attributes.

This is what I have tried so far and it is not working:

out = [[i for i, v in lst if v > -200 else i == i[0]] for _, lst in predictions]

Thanks for the help

I think you mean this:

out = [[i for i, v in lst if v > -200] or [lst[0][0]] for _, lst in predictions]

However as you can see, the fact it is hard to get too and to explain what it does, means that sometimes it is better to just write code in an explicit form:

out = []
for _, lst in prediction:
   member = [i for i, v in lst if v > -200]
   if not member:
       member = [lst[0][0]]
   out.append(member)

Note on the first form: the operators "or" and "and" in Python behave differently most other binary operators. "or" will evaluate to the object on its left side if it has a "truthy" value, otherwise to the object on the right side (regardless of it having a True value or not). Then, in Python, an empty sequence has a "falsy" value (it evaluates to boolean False), so, if the elements filtered by the "> -200" guard end-up empty, the "or" in there will pick the result of the expression to the right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM