【问题标题】:PyTorch Custom Batch FunctionPyTorch 自定义批处理函数
【发布时间】:2021-10-01 02:15:50
【问题描述】:

假设我有一个 DataLoader

dataloader = DataLoader(dataset, batch_size=32)

我想定义一个可以前馈我的自定义函数的神经网络。我知道在传统的全连接网络中,我可以只使用它的线性或其他已经存在的功能。而且,重要的是,这些函数可以使用 DataLoader 输入并自动批处理运行。

现在我想定义我自己的函数,但我不知道如何编写它没有for循环。比如(我随机写了一些自定义函数f(x)),

def f(x):
    x = np.sin(np.exp(x)) + np.log(x) - 1/x
    return x

class NeuralNet(nn.Module):
    def __init__(self, input_dim):
        super(NeuralNet, self).__init__()
        self.net = f
    def forward(self, x_batch):
        result = torch.zeros(len(x_batch))
        for i in len(x_batch):
            result[i] = self.net(x_batch[i])
        return result

或者 f 中的 for 循环

def f(x_batch):
    result = torch.zeros(len(x_batch))
    for i in range(x_batch):
        result[i] = np.sin(np.exp(x_batch[i])) + np.log(x_batch[i]) - 1/x_batch[i]
    return result

class NeuralNet(nn.Module):
    def __init__(self, input_dim):
        super(NeuralNet, self).__init__()
        self.net = f
    def forward(self, x_batch):
        return self.net(x_batch)

有什么办法可以摆脱 for 循环,以便在 GPU 上进行并行计算?因为我认为 for 循环不会利用 GPU 的优势。还是我误会了什么?

【问题讨论】:

    标签: pytorch


    【解决方案1】:

    在 PyTorch 中实现的基本数学运算符可以开箱即用地使用 n 维张量。如果您以这种方式定义 f 函数,您可以一次性喂完整个批次。

    在你的情况下,你可以这样做:

    def f(x):
        x = torch.sin(torch.exp(x)) + torch.log(x) - 1/x
        return x
    
    class NeuralNet(nn.Module):
        def __init__(self):
            super(NeuralNet, self).__init__()
            self.net = f
    
        def forward(self, x_batch):
            result = self.net(x_batch)
            return result
    
    >>> net = NeuralNet()
    >>> net(torch.tensor([[1,2,3]]))
    

    如果您坚持使用 PyTorch 运算符(大多数都实现了后向功能)并且在某些时候不要切换到 Numpy。然后你就可以在你的模型上调用反向传递。

    当然,所有这些计算都可以在 GPU 上进行!

    【讨论】:

    • 非常感谢您的精彩解释!但是,很抱歉我的函数不是简单的基本数学运算。我需要前馈的函数是‘量子电路’(可以查pennylane.readthedocs.io/en/stable/introduction/interfaces/…
    • 从文档看来,您仍然可以使用 PyTorch 接口来计算反向传递。换句话说,pennylane 提供的功能是在 PyTorch 中实现的。
    【解决方案2】:

    【讨论】:

    • 嗯,看来你自己回答了。
    猜你喜欢
    • 2021-10-23
    • 1970-01-01
    • 2020-03-01
    • 2019-05-27
    • 2019-02-28
    • 2021-11-13
    • 2022-01-23
    • 2018-09-24
    • 2017-05-17
    相关资源
    最近更新 更多