gpt4 book ai didi

julia - @with_kw 在 Julia 中做什么?

转载 作者:行者123 更新时间:2023-12-05 04:43:37 24 4
gpt4 key购买 nike

我正在阅读一些看起来像这样的代码:

 @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_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))

关于julia - @with_kw 在 Julia 中做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69586136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com