Pytorch data.random_split() 不会随机分裂

Pytorch data.random_split() doesn't split randomly

我正在尝试将我的自定义数据集 运行domly 拆分为测试和训练。代码运行并成功输出测试和训练文件夹,但每次 运行 代码时我都需要不同的测试和训练集。这不是 运行domly 分裂应该 mean/do 吗?

p.s。只是为了澄清,数据是图像,所以我希望每次执行代码时都能看到为测试和训练集选择的不同图像。

#Set the random seeds for reproducibility
SEED = 1234

random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
torch.cuda.manual_seed(SEED)
torch.backends.cudnn.deterministic = True

TRAIN_RATIO = 0.9

data_dir = 'Data Set 1'
images_dir = os.path.join(data_dir, 'images')
train_dir = os.path.join(data_dir, 'train')
test_dir = os.path.join(data_dir, 'test')

if os.path.exists(train_dir):
    shutil.rmtree(train_dir)
if os.path.exists(test_dir):
    shutil.rmtree(test_dir)

os.makedirs(train_dir)
os.makedirs(test_dir)

classes = os.listdir(images_dir)

for c in classes:

    class_dir = os.path.join(images_dir, c)

    images = os.listdir(class_dir)

    n_train = int(len(images) * TRAIN_RATIO)
    n_test = len(images) - n_train
    train_images, test_images = data.random_split(images,
                                               [n_train, n_test])

    os.makedirs(os.path.join(train_dir, c), exist_ok=True)
    os.makedirs(os.path.join(test_dir, c), exist_ok=True)

    for image in train_images:
        image_src = os.path.join(class_dir, image)
        image_dst = os.path.join(train_dir, c, image)
        shutil.copyfile(image_src, image_dst)

    for image in test_images:
        image_src = os.path.join(class_dir, image)
        image_dst = os.path.join(test_dir, c, image)
        shutil.copyfile(image_src, image_dst)





它不是随机的,因为您设置了随机种子。将种子想象成一个随机数——如果你定义了种子,这个数字就不再是随机的了。如果你不定义它,你每次都会得到一个随机种子。 只需注释掉这些行:)

SEED = 1234

random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
torch.cuda.manual_seed(SEED)

或者,只需执行以下操作:SEED = random.randint(1, 1000) 以获得 1 到 1000 之间的随机数。如果您出于某种原因需要它,这将让您打印 SEED 的值。

您可以在此处查看种子函数的工作原理: https://www.w3schools.com/python/ref_random_seed.asp