“ x:”和以下行的含义是什么?

时间:2019-04-22 10:21:01

标签: python python-3.x pytorch

x:和下一行的含义是什么?

image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),
                                          data_transforms[x])

有人可以解释这一行的语法吗?

来自PyTorch教程: https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html

# Data augmentation and normalization for training
# Just normalization for validation
data_transforms = {
    'train': transforms.Compose([
        transforms.RandomResizedCrop(224),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
    'val': transforms.Compose([
        transforms.Resize(256),
        transforms.CenterCrop(224),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
}

data_dir = 'data/hymenoptera_data'
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),
                                          data_transforms[x])
                  for x in ['train', 'val']}
dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=4,
                                             shuffle=True, num_workers=4)
              for x in ['train', 'val']}
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}
class_names = image_datasets['train'].classes

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

2 个答案:

答案 0 :(得分:1)

image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),
                                          data_transforms[x])
                  for x in ['train', 'val']}

x来自下面的forfor x in ['train', 'val'],因此对于['train', 'val']中的每个值,您正在创建一个dict为键的x

Kabanus 所说,这种结构是字典理解,字典生成器。

您可以在此处了解有关生成器的更多信息:https://docs.python.org/3/tutorial/classes.html#generators

答案 1 :(得分:0)

{x: "data/hymenoptera_data/"+x for x in ['train', 'val']}

结果将是:

{'train': 'data/hymenoptera_data/train', 'val': 'data/hymenoptera_data/val'}

基本上,它从列表中获取每个字符串并形成一个包含两个项目的字典。