如何从列表中随机选择连续样本?

Stu*_*PhD 2 python random numpy

我有不同深度的输入数组,范围从 20 到 32。我无法填充它们以使它们全部具有相同的大小,因此最好的选择是在每次迭代时随机选择图像的 z 深度。

我读过numpy.random.choice()可以用于此目的,但我得到了随机排列的索引,我想要连续的选择。

z_values = np.arange(img.shape[0]) # get the depth of this sample
z_rand = np.random.choice(z_values, 20) # create an index array for croping
Run Code Online (Sandbox Code Playgroud)

上面给了我:

[22  4 31 19  9 24 13  6 20 17 28  8 11 27 14 15 30 16 12 25]
Run Code Online (Sandbox Code Playgroud)

这对我来说没有用,因为它们不连续,我不能用它来裁剪我的音量。

有没有办法获得连续的随机样本?

谢谢

Par*_*ngh 5

如果我理解正确的话,你想随机选择一个 20 长度的切片。因此,只需调整您的逻辑以随机搜索有效的起点,然后进行切片即可获得您需要的结果。

import numpy as np
import random
#pretending this is the image
img = np.array(range(100, 3200, 100))

size_to_slice = 20
if img.shape[0] >= size_to_slice: #make sure you are able to get the length you need
    start = random.randint(0, img.shape[0] - size_to_slice)    
    z_rand = img[start: start + size_to_slice]
else:
    print("selection invalid")
Run Code Online (Sandbox Code Playgroud)