gpt4 book ai didi

julia - Julia 中的双广播矩阵向量加法?

转载 作者:行者123 更新时间:2023-12-03 23:04:06 25 4
gpt4 key购买 nike

新手 Julia 问题在这里。给定两个数组,

W = [randn(3,2), randn(3,2)]
b = [randn(3), randn(3)]
我想按照以下方式进行“嵌套广播”,
W .+ b = [W[1].+b[1], W[2].+b[2]]
到目前为止,我能想到的最好的是,
[Wi.+bi (Wi,bi) for zip(W,b)]
来自 Python 背景,这感觉很亵渎。在 Julia 中有更好的方法来做到这一点吗?

最佳答案

您可以执行以下操作:

julia> W = [randn(3,2), randn(3,2)]
2-element Array{Array{Float64,2},1}:
[0.39179718902868116 -0.5387622679356612; -0.594274465053327 0.018804631512093436; -2.273706742420988 -0.4638617400026042]
[0.3249960563405678 -0.4877554417492699; 0.5036437919340767 1.3172770503034696; 0.03501532820428975 -0.2675024677340758]

julia> b = [randn(3), randn(3)]
2-element Array{Array{Float64,1},1}:
[1.2571527266220441, 0.21599608118129476, 0.21498843153804936]
[-0.528960345932853, 0.5610435189953311, -0.8636370930615718]

# A helper function which broadcasts once
julia> s_(Wi, bi) = Wi .+ bi
s_ (generic function with 1 method)

# Broadcast the helper function
julia> s_.(W, b)
2-element Array{Array{Float64,2},1}:
[1.6489499156507252 0.718390458686383; -0.3782783838720323 0.2348007126933882; -2.0587183108829388 -0.24887330846455485]
[-0.20396428959228524 -1.016715787682123; 1.0646873109294077 1.8783205692988008; -0.828621764857282 -1.1311395607956476]

如评论中所述,您可以使用可用的 user-definable infix operators 之一。命名辅助函数,它允许更好的语法(下面使用的特定符号可以通过键入 \oplus 然后 Tab 获得):
julia> ⊕(x, y) = x .+ y
⊕ (generic function with 1 method)

julia> W .⊕ b
2-element Array{Array{Float64,2},1}:
[1.6489499156507252 0.718390458686383; -0.3782783838720323 0.2348007126933882; -2.0587183108829388 -0.24887330846455485]
[-0.20396428959228524 -1.016715787682123; 1.0646873109294077 1.8783205692988008; -0.828621764857282 -1.1311395607956476]


或者 - 再次如评论中所述 - 如果您不想明确声明辅助函数:
julia> ((Wi, bi)->Wi.+bi).(W, b)
2-element Array{Array{Float64,2},1}:
[1.6489499156507252 0.718390458686383; -0.3782783838720323 0.2348007126933882; -2.0587183108829388 -0.24887330846455485]
[-0.20396428959228524 -1.016715787682123; 1.0646873109294077 1.8783205692988008; -0.828621764857282 -1.1311395607956476]
(我个人更难阅读上一个版本,但 YMMV)

关于julia - Julia 中的双广播矩阵向量加法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63780190/

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