根据条件获取随机元素

Tom*_*aga 1 python random numpy

我有两个列表:图像和相应的标签。我想通过给定的标签获得随机图像。我想过使用 numpy 数组来获取布尔数组,然后使用 list.index。问题是它返回第一次出现的索引。有任何想法吗?

Gra*_*her 6

使用numpy.where获取数组包含在条件为真,然后使用索引numpy.random.choice来随机选择一个:

import numpy as np
# to always get the same result
np.random.seed(42)

# setup data
images = np.arange(10)
labels = np.arange(10)

# select on the labels
indices = np.where(labels % 2 == 0)[0]
print(indices)
# [0, 2, 4, 6, 8]

# choose one
random_image = images[np.random.choice(indices)]
print(random_image)
# 6
Run Code Online (Sandbox Code Playgroud)

你可能想把它放在一个函数中:

from numpy import where
from numpy.random import choice

def random_img_with_label(images, labels, label):
    indices = where(labels == label)[0]
    return images[choice(indices)]
Run Code Online (Sandbox Code Playgroud)

或者,您可以直接根据您的条件创建蒙版并从中选择:

random_image = np.random.choice(images[labels % 2 == 0])
Run Code Online (Sandbox Code Playgroud)