Julia中的@with_kw有什么作用?

3

我在阅读一些代码,它看起来像:

 @with_kw struct HyperParams
     batch_size::Int = 128
     latent_dim::Int = 100
     epochs::Int = 25
     verbose_freq::Int = 1000
     output_dim::Int = 5
     disc_lr::Float64 = 0.0002
     gen_lr::Float64 = 0.0002
     device::Function = gpu
 end

但是我不清楚在这个上下文中@with_kw的作用是什么。它是否仍然是一个普通的结构体?它看起来并不像是基本Julia的一部分,因此我对其在这里的使用不熟悉。


1个回答

3
所以看起来@with_kwParameters包的一部分,它提供了为结构体字段和关键字参数定义默认值的功能。根据Julia文档,这里:https://docs.julialang.org/en/v1/manual/types/#Composite-Types,似乎无法定义默认值,所以在这种情况下它实际上非常有用。以下是使用关键字参数和默认值的示例:
julia> @with_kw struct HyperParams
            batch_size::Int = 128
            latent_dim::Int = 100
            epochs::Int = 25
            verbose_freq::Int = 1000
            output_dim::Int = 5
            disc_lr::Float64 = 0.0002
            gen_lr::Float64 = 0.0002
            device::Function
        end
HyperParams

julia> hyper = HyperParams(device=cpu)
HyperParams
  batch_size: Int64 128
  latent_dim: Int64 100
  epochs: Int64 25
  verbose_freq: Int64 1000
  output_dim: Int64 5
  disc_lr: Float64 0.0002
  gen_lr: Float64 0.0002
  device: cpu (function of type typeof(cpu))


julia> HyperParams()
ERROR: Field 'device' has no default, supply it with keyword.
Stacktrace:
 [1] error(s::String)
   @ Base ./error.jl:33
 [2] HyperParams()
   @ Main ~/.julia/packages/Parameters/MK0O4/src/Parameters.jl:493
 [3] top-level scope
   @ REPL[61]:1

julia> hyper = HyperParams(epochs=20, device=cpu)
HyperParams
  batch_size: Int64 128
  latent_dim: Int64 100
  epochs: Int64 20
  verbose_freq: Int64 1000
  output_dim: Int64 5
  disc_lr: Float64 0.0002
  gen_lr: Float64 0.0002
  device: cpu (function of type typeof(cpu))


2
这与 Base.@kwdef 有何不同? - Sundar R
好问题,我们可能应该为此发布不同的帖子。 - logankilpatrick
https://dev59.com/0moMtIcB2Jgan1znjX2J#69605857 - logankilpatrick

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接