首页 > 解决方案 > Julia中函数调用的歧义

问题描述

我有这个错误

ERROR: MethodError: vcat(::Array{Real,2}, ::TrackedArray{…,Array{Float32,2}}) is ambiguous. Candidates:
  vcat(364::AbstractArray, x::Union{TrackedArray, TrackedReal}, xs::Union{Number, AbstractArray}...) in Tracker at C:\Users\Henri\.julia\packages\Tracker\6wcYJ\src\lib\array.jl:167
  vcat(A::Union{AbstractArray{T,2}, AbstractArray{T,1}} where T...) in Base at abstractarray.jl:1296
Possible fix, define
  vcat(::Union{AbstractArray{T,2}, AbstractArray{T,1}} where T, ::Union{TrackedArray{T,1,A} where A<:AbstractArray{T,1} where T, TrackedArray{T,2,A} where A<:AbstractArray{T,2} where T}, ::Vararg{Union{AbstractArray{T,2}, AbstractArray{T,1}} where T,N} where N)

告诉我两个vcat()函数是模棱两可的。我想使用该Base.vcat()函数,但显式使用它会引发相同的错误。这是为什么 ?错误抛出提出的这个“可能的修复”是什么?

此外,当我手动调用 REPL 中的每一行时,不会引发错误。我不明白这种行为。这只发生在 vcat() 位于另一个函数内部调用的函数中时。就像我下面的例子一样。

这是重现错误的代码:

using Flux

function loss(a, b, net, net2)
    net2(vcat(net(a),a))

end

function test()    
    opt = ADAM()
    net = Chain(Dense(3,3))
    net2 = Chain(Dense(6,1))
    L(a, b) = loss(a, b, net, net2)

    data = tuple(rand(3,1), rand(3,1))
    xs = Flux.params(net)
    gs = Tracker.gradient(() -> L(data...), xs)
    Tracker.update!(opt, xs, gs)
end

标签: juliaambiguity

解决方案


正如在 Henri.D 的评论中提到的,我们已经设法通过谨慎处理它的类型来修复它,其中的类型aArrayof Float64,默认类型由返回,randnet(a)返回的类型是TrackedArrayof ,Float32并且不可能vcat使用a.

我已经设法vcat通过改变你的损失函数来解决这个问题:net2(vcat(net(a),Float32.(a)))因为vcat不能像net(a)aFloat32 Arrayaa那样连接Float64。然后L(data...)TrackedArray1 个元素,而我认为您需要 aFloat32这就是为什么我最终替换loss functionnet2(vcat(net(a),Float32.(a)))[1]


推荐阅读