作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在阅读一些看起来像这样的代码:
@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 的一部分,所以我不熟悉它在这里的用法。
最佳答案
所以看起来 @with_kw
是 Parameters
包的一部分,它提供了为结构字段和关键字参数定义默认值的能力。根据此处的 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))
关于julia - @with_kw 在 Julia 中做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69586136/
我正在阅读一些看起来像这样的代码: @with_kw struct HyperParams batch_size::Int = 128 latent_dim::Int = 100
我想将 @assert 宏与结构一起使用。 来自包 Parameters 的 @with_kw 宏可以不使用构建在结构之上的显式方法,而 Base.@kwdef 需要显式方法。我理解正确吗? # 1.
我是一名优秀的程序员,十分优秀!