如何在 Julia 中替换 python 的属性

How to replace the use of python's attributes in Julia

我有一些 Python 形式的函数 fast.ai 课程:

def mse_grad(inp, targ): 
    # grad of loss with respect to output of previous layer
    inp.g = 2. * (inp.squeeze() - targ).unsqueeze(-1) / inp.shape[0]

def lin_grad(inp, out, w, b):
    # grad of matmul with respect to input
    inp.g = out.g @ w.t()
    w.g = (inp.unsqueeze(-1) * out.g.unsqueeze(1)).sum(0)
    b.g = out.g.sum(0)

def forward_and_backward(inp, targ):
    # backward pass:
    mse_grad(out, targ)
    lin_grad(l2, out, w2, b2)

它使用了python的属性。我如何在 Julia 中替换这个 inp.g 和 out.g 以便我可以在 forward_and_backward 函数中使用这些函数以便它们可以访问彼此的梯度?

只需使用 'g' 作为字段定义您自己的结构。参见 https://docs.julialang.org/en/v1/manual/types/#Composite-Types-1

Julia 1.0 Tutorials - Structs and Mutable Structs(Types)