如何在python类代码中再添加一个批处理大小维

问题描述

我正在学习注意力机制,并从github上看到了某人的代码,如下所示:

userPrincipalName

如何重新编写以上代码以包含一个以上的“批量大小”?

谢谢你, 灵

解决方法

在Pytorch中,您不必在模型类中为batchsize指定任何内容。您只需要确保输入(在您的情况下为“ F”)具有尺寸(B,C,W,H),B是批处理尺寸。您可以通过自己创建图像的张量或使用dataloader来实现。您必须使用以下结构为数据集创建自己的类:


class YourDataset(torch.utils.data.Dataset):
    def __init__(self,datase):
        """ constructor
        load your dataset here,dataset could be a csv file or a list or whatever you want
        """

    def __getitem__(self,i)
        """ get sample from dataset
        :param int i: index of dataset (iterator of training-loop)
        :return tensor: preprocessed sample and target

        preprocess the i'th sample/image here if necessary and/or just return the image 
        and its label
        """
    def __len__(self):
        """ returns length of dataset """

在这里,您仍然没有指定有关batchsize的任何信息,但这是数据加载器随附的,您可以这样创建:

dataset = YourDataset(dataset_file_or_whatever)
dataloder = torch.utils.data.DataLoader(
        dataset,batch_size=64,num_workers=1,shuffle=True)

并且知道您可以在火车循环中遍历数据loder,例如:

for epoch in range(epochs):
    for images,targets in dataloader:
        # images and targets will now have the dimensions (B,C,W,H)!
        # thats it! Now you can train with batches

我希望这能回答您的问题!

修改 刚刚看到它不是真的,但是我写了所有这些东西,所以imma让它站在这里,希望它对那些不知道的人仍然有用

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...